: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): add Bigeye import source (#84310)
Tom Owerse269e603c694
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/bigeye.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/bigeye.pynew file mode 100644index 000000000000..9627130d9094--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/bigeye.py@@ -0,0 +1,207 @@+import re+from typing import Any, Optional, cast++import requests++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.settings import (+ BIGEYE_ENDPOINTS,+ REQUEST_TIMEOUT_SECONDS,+)+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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+ HTTPMethodBasic,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++DEFAULT_HOST = "app.bigeye.com"++# Bigeye's `.../fetch` endpoints (Sources, Tables, Issues) don't publish a page-size cap; this is+# a conservative default that keeps individual responses small on large workspaces.+PAGE_SIZE = 100++# The exact body of the 400 Bigeye returns when a multi-workspace tenant omits `workspaceId`+# (docs.bigeye.com/docs/api-user-guide). Matched in get_non_retryable_errors so the user is told+# to set the Workspace ID field instead of retrying forever.+WORKSPACE_ID_REQUIRED_MESSAGE = "A workspace ID must be supplied"++_HOST_RE = re.compile(r"^https?://", re.IGNORECASE)+++@frozen+class BigeyeResumeConfig:+ next_cursor: str+++def normalize_host(host: Optional[str]) -> str:+ """Accept a bare host, a full URL, or an empty value (falls back to the SaaS default)."""+ if not host or not host.strip():+ return DEFAULT_HOST+ normalized = _HOST_RE.sub("", host.strip())+ return normalized.split("/")[0].rstrip("/")+++def _base_url(host: Optional[str]) -> str:+ return f"https://{normalize_host(host)}"+++def _auth_header_value(api_key: str) -> str:+ return f"apikey {api_key}"+++def _flatten_collection(item: dict[str, Any]) -> dict[str, Any]:+ # Collection rows nest their identity under `collectionConfiguration`; copy `id`/`name` to the+ # row root so the pipeline's primary-key column ("id") and table naming are top-level fields,+ # while keeping the full nested payload for anyone querying the raw JSON columns.+ config = item.get("collectionConfiguration") or {}+ return {**item, "id": config.get("id"), "name": config.get("name")}+++def get_resource(name: str, workspace_id: Optional[int]) -> EndpointResource:+ endpoint_config = BIGEYE_ENDPOINTS[name]++ endpoint: Endpoint = {+ "path": endpoint_config.path,+ "method": cast(HTTPMethodBasic, endpoint_config.method),+ "data_selector": endpoint_config.data_selector,+ }++ if endpoint_config.paginated:+ body: dict[str, Any] = {"pageSize": PAGE_SIZE}+ if workspace_id is not None:+ body["workspaceId"] = workspace_id+ endpoint["json"] = body+ endpoint["paginator"] = JSONResponseCursorPaginator(+ cursor_path="paginationInfo.nextCursor",+ cursor_param="pageCursor",+ param_location="json",+ )+ else:+ endpoint["paginator"] = SinglePagePaginator()+ if name == "Collections" and workspace_id is not None:+ endpoint["params"] = {"workspaceId": workspace_id}++ resource: EndpointResource = {+ "name": name,+ "table_name": endpoint_config.table_name,+ "write_disposition": "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+ if name == "Collections":+ resource["data_map"] = _flatten_collection+ return resource+++def bigeye_source(+ api_key: str,+ host: Optional[str],+ workspace_id: Optional[int],+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[BigeyeResumeConfig],+) -> SourceResponse:+ endpoint_config = BIGEYE_ENDPOINTS[endpoint]++ config: RESTAPIConfig = {+ "client": {+ "base_url": _base_url(host),+ "auth": {+ "type": "api_key",+ "api_key": _auth_header_value(api_key),+ "name": "Authorization",+ "location": "header",+ },+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ # A validated host could 3xx to an internal address; refuse to follow redirects (SSRF).+ "allow_redirects": False,+ },+ "resource_defaults": {},+ "resources": [get_resource(endpoint, workspace_id)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if endpoint_config.paginated and resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.next_cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the manager's Redis TTL handles+ # cleanup once the sync completes.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(BigeyeResumeConfig(next_cursor=str(state["cursor"])))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint if endpoint_config.paginated else None,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=[endpoint_config.primary_key],+ column_hints=resource.column_hints,+ # None of these tables expose a stable datetime field worth partitioning on (see+ # settings.py) — small metadata catalogs, full refresh only.+ partition_count=1,+ partition_size=1,+ )+++def validate_credentials(+ api_key: str,+ host: Optional[str],+ workspace_id: Optional[int],+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Probe the workspaces list, the cheapest endpoint that needs no workspace scoping."""+ normalized_host = normalize_host(host)++ if team_id is not None:+ host_ok, host_err = _is_host_safe(normalized_host, team_id)+ if not host_ok:+ return False, host_err or "That Bigeye host is not allowed."++ url = f"https://{normalized_host}/api/v1/workspaces"+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ url,+ headers={"Authorization": _auth_header_value(api_key)},+ timeout=10,+ allow_redirects=False,+ )+ except requests.exceptions.RequestException as e:+ return False, f"Could not reach Bigeye: {e}"++ if response.is_redirect or response.is_permanent_redirect:+ return False, "That Bigeye host is not allowed."++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Bigeye API key. Please check your key and try again."++ if response.status_code == 403:+ return False, "Your Bigeye API key does not have permission to list workspaces."++ return False, f"Bigeye returned an unexpected error (HTTP {response.status_code})."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/canonical_descriptions.pynew file mode 100644index 000000000000..72681bd94bbc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/canonical_descriptions.py@@ -0,0 +1,80 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Workspaces": {+ "description": "A Bigeye workspace: an isolated collection of connected data sources, tables, and metrics.",+ "docs_url": "https://docs.bigeye.com/reference/workspaceservice_getallworkspaces-1",+ "columns": {+ "id": "Unique identifier for the workspace.",+ "name": "Display name of the workspace.",+ "isDefault": "Whether this is the account's default workspace.",+ },+ },+ "Sources": {+ "description": "A data source (database or warehouse) connected to Bigeye for monitoring.",+ "docs_url": "https://docs.bigeye.com/reference/sourceservice_getsources-1",+ "columns": {+ "id": "Unique identifier for the source.",+ "name": "Display name of the source.",+ "databaseType": "The underlying database or warehouse technology (e.g. Snowflake, BigQuery, Postgres).",+ "hostname": "Hostname Bigeye connects to for this source.",+ "databaseName": "Name of the database or catalog within the source.",+ "isFavorite": "Whether the source is marked as a favorite in the Bigeye UI.",+ "usesAgent": "Whether this source connects through a self-hosted Bigeye agent instead of directly.",+ "agentHealthStatus": "Health status of the connecting agent, when one is used.",+ },+ },+ "Tables": {+ "description": "A table or view discovered by Bigeye within a connected source.",+ "docs_url": "https://docs.bigeye.com/reference/tableservice_gettables-1",+ "columns": {+ "id": "Unique identifier for the table.",+ "name": "Table name.",+ "schemaId": "Identifier of the schema the table belongs to.",+ "schemaName": "Name of the schema the table belongs to.",+ "warehouseId": "Identifier of the source (warehouse) the table belongs to.",+ "warehouseName": "Name of the source (warehouse) the table belongs to.",+ "databaseName": "Name of the database the table belongs to.",+ "tableType": "Whether this is a table, view, or another object type.",+ "isFavorite": "Whether the table is marked as a favorite in the Bigeye UI.",+ "logicalSizeBytes": "Logical size of the table in bytes, as last observed.",+ },+ },+ "Metrics": {+ "description": "A configured data quality metric (a check Bigeye runs on a column or table).",+ "docs_url": "https://docs.bigeye.com/reference/metricservice_searchmetricconfiguration-1",+ "columns": {+ "id": "Unique identifier for the metric.",+ "name": "Display name of the metric.",+ "description": "Free-text description of what the metric checks.",+ "datasetId": "Identifier of the table the metric observes.",+ "warehouseId": "Identifier of the source the metric's table belongs to.",+ "mutedUntilEpochSeconds": "Unix timestamp (seconds) the metric's alerts are muted until, if muted.",+ },+ },+ "Collections": {+ "description": "A named group of metrics, used to organize monitoring and route alert notifications.",+ "docs_url": "https://docs.bigeye.com/reference/collectionservice_getcollectioninfos-1",+ "columns": {+ "id": "Unique identifier for the collection.",+ "name": "Display name of the collection.",+ },+ },+ "Issues": {+ "description": "An open or resolved data quality issue, created when one of a collection's metrics alerts.",+ "docs_url": "https://docs.bigeye.com/reference/issueservice_getissues-1",+ "columns": {+ "id": "Unique identifier for the issue.",+ "name": "Short display name of the issue.",+ "summary": "One-line summary of the issue.",+ "description": "Longer free-text description of the issue.",+ "currentStatus": "Current triage status of the issue (e.g. new, acknowledged, monitoring, resolved).",+ "priority": "Priority Bigeye assigned to the issue.",+ "openedTimeSeconds": "Unix timestamp (seconds) the issue was first opened.",+ "closedTimeSeconds": "Unix timestamp (seconds) the issue was closed, if resolved.",+ "metricIds": "Identifiers of the metrics alerting on this issue.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/settings.pynew file mode 100644index 000000000000..9a08185fef66--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/settings.py@@ -0,0 +1,93 @@+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++FetchMethod = Literal["get", "post"]++# (connect, read) timeout for sync requests against the user-configured host. Bounds how long a+# stalled or slow-responding custom host can occupy an import worker; the credential probe in+# bigeye.py uses its own shorter timeout.+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)+++@frozen+class BigeyeEndpointConfig:+ name: str+ table_name: str+ path: str+ method: FetchMethod+ # Key in the JSON response body that holds the list of rows.+ data_selector: str+ # True for the `POST .../fetch` endpoints that page via a `pageCursor` in the JSON body.+ # False for the small GET endpoints that return their full result in one response.+ paginated: bool+ primary_key: str = "id"+++# Bigeye's v1 API has no documented "updated since" filter on any list endpoint (see+# INCREMENTAL_FIELDS below), so every table here is full refresh. The `.../fetch` endpoints are+# still resumable via their `pageCursor`, which matters for large workspaces (many sources/tables/+# issues) surviving a heartbeat timeout mid-sync.+BIGEYE_ENDPOINTS: dict[str, BigeyeEndpointConfig] = {+ "Workspaces": BigeyeEndpointConfig(+ name="Workspaces",+ table_name="workspaces",+ path="/api/v1/workspaces",+ method="get",+ data_selector="workspaces",+ paginated=False,+ ),+ "Sources": BigeyeEndpointConfig(+ name="Sources",+ table_name="sources",+ path="/api/v1/sources/fetch",+ method="post",+ data_selector="sources",+ paginated=True,+ ),+ "Tables": BigeyeEndpointConfig(+ name="Tables",+ table_name="tables",+ path="/api/v1/tables/fetch",+ method="post",+ data_selector="tables",+ paginated=True,+ ),+ "Metrics": BigeyeEndpointConfig(+ name="Metrics",+ table_name="metrics",+ path="/api/v1/metrics",+ method="get",+ data_selector="metrics",+ paginated=False,+ ),+ "Collections": BigeyeEndpointConfig(+ name="Collections",+ table_name="collections",+ path="/api/v1/collections/info",+ method="get",+ data_selector="collectionInfos",+ paginated=False,+ # Rows nest their id under `collectionConfiguration.id`; `_flatten_collection` copies it+ # to the top level before this primary key is applied.+ primary_key="id",+ ),+ "Issues": BigeyeEndpointConfig(+ name="Issues",+ table_name="issues",+ path="/api/v1/issues/fetch",+ method="post",+ # Bigeye's issue-list response wraps rows under the singular key `issue`, not `issues`.+ data_selector="issue",+ paginated=True,+ ),+}++ENDPOINTS = tuple(BIGEYE_ENDPOINTS.keys())++# No endpoint exposes a server-side "updated since" / "modified after" filter in the published+# API reference, so nothing here can be a true incremental sync (see the module docstring in+# bigeye.py for what was checked). Every table syncs full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/source.pyindex 173077796e78..437e9b9569a1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/source.py@@ -1,30 +1,152 @@-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.sources.bigeye.bigeye import (+ WORKSPACE_ID_REQUIRED_MESSAGE,+ BigeyeResumeConfig,+ bigeye_source,+ validate_credentials as validate_bigeye_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigeye import BigeyeSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class BigeyeSource(SimpleSource[BigeyeSourceConfig]):+class BigeyeSource(ResumableSource[BigeyeSourceConfig, BigeyeResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ # Bigeye's REST API has no dated or numbered version token (see docs.bigeye.com/reference) —+ # every path is a bare `/api/v1/...` that has never changed.+ api_docs_url = "https://docs.bigeye.com/reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BIGEYE+ @property+ def connection_host_fields(self) -> list[str]:+ # `host` is where the stored API key is sent; retargeting it must re-require the key.+ return ["host"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Bigeye API key. Please generate a new key and reconnect.",+ "403 Client Error": "Your Bigeye API key does not have permission for this data. Please check the key's role and try again.",+ WORKSPACE_ID_REQUIRED_MESSAGE: (+ "This Bigeye account has more than one workspace. Please set the Workspace ID field and reconnect."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: BigeyeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: BigeyeSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_bigeye_credentials(config.api_key, config.host, config.workspace_id, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BigeyeResumeConfig]:+ return ResumableSourceManager[BigeyeResumeConfig](inputs, BigeyeResumeConfig)++ def source_for_pipeline(+ self,+ config: BigeyeSourceConfig,+ resumable_source_manager: ResumableSourceManager[BigeyeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return bigeye_source(+ api_key=config.api_key,+ host=config.host,+ workspace_id=config.workspace_id,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.BIGEYE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Bigeye",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a Bigeye API key to pull your data observability metadata into the PostHog Data warehouse.++Generate a Personal or Agent API key from **Advanced Settings** in your Bigeye workspace. The key inherits your Bigeye role's access (view, edit, or manage).""",iconPath="/static/services/bigeye.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/bigeye",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="host",+ label="Bigeye host",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="app.bigeye.com",+ caption="Leave blank unless your organization uses a self-hosted or regional Bigeye instance.",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="workspace_id",+ label="Workspace ID",+ type=SourceFieldInputConfigType.NUMBER,+ required=False,+ placeholder="",+ caption="Only needed if your Bigeye account has more than one workspace. Find it in workspace settings.",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/tests/test_bigeye.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/tests/test_bigeye.pynew file mode 100644index 000000000000..b0b36007ce50--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/tests/test_bigeye.py@@ -0,0 +1,372 @@+import json+from typing import Any, cast++import pytest+from unittest import mock++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye import bigeye as bigeye_module+from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.bigeye import (+ BigeyeResumeConfig,+ _auth_header_value,+ _base_url,+ _flatten_collection,+ bigeye_source,+ get_resource,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.settings import (+ BIGEYE_ENDPOINTS,+ REQUEST_TIMEOUT_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the bigeye module.+BIGEYE_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.bigeye.make_tracked_session"+)+++def _response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: BigeyeResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT PREPARE TIME.++ ``request.params`` / ``request.json`` are single dicts mutated in place across pages, so+ inspecting them after the run shows only the final state — snapshot copies when each request+ is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append(+ {+ "method": request.method,+ "url": request.url,+ "params": dict(request.params or {}),+ "json": dict(request.json) if request.json is not None else None,+ }+ )+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _build(endpoint: str, manager: mock.MagicMock, host: str | None = None, workspace_id: int | None = None) -> Any:+ return bigeye_source(+ api_key="key",+ host=host,+ workspace_id=workspace_id,+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (None, "app.bigeye.com"),+ ("", "app.bigeye.com"),+ (" ", "app.bigeye.com"),+ ("app.bigeye.com", "app.bigeye.com"),+ ("https://app.bigeye.com", "app.bigeye.com"),+ ("https://app.bigeye.com/", "app.bigeye.com"),+ ("http://bigeye.internal.example.com/api", "bigeye.internal.example.com"),+ ],+ )+ def test_normalizes(self, value: str | None, expected: str) -> None:+ assert normalize_host(value) == expected++ def test_base_url_defaults_to_saas_host(self) -> None:+ assert _base_url(None) == "https://app.bigeye.com"++ def test_base_url_honors_custom_host(self) -> None:+ assert _base_url("bigeye.internal.example.com") == "https://bigeye.internal.example.com"+++class TestFlattenCollection:+ def test_copies_id_and_name_to_root(self) -> None:+ item = {"collectionConfiguration": {"id": 42, "name": "Nightly checks"}, "collectionMetricStatus": {}}+ flattened = _flatten_collection(item)+ assert flattened["id"] == 42+ assert flattened["name"] == "Nightly checks"+ assert flattened["collectionConfiguration"] == {"id": 42, "name": "Nightly checks"}++ def test_missing_configuration_does_not_raise(self) -> None:+ assert _flatten_collection({}) == {"id": None, "name": None}+++class TestGetResource:+ @pytest.mark.parametrize("name", list(BIGEYE_ENDPOINTS.keys()))+ def test_every_endpoint_builds_a_resource(self, name: str) -> None:+ resource = cast(dict[str, Any], get_resource(name, workspace_id=None))+ assert resource["name"] == name+ assert resource["endpoint"]["path"] == BIGEYE_ENDPOINTS[name].path++ def test_paginated_endpoint_omits_workspace_id_when_unset(self) -> None:+ resource = cast(dict[str, Any], get_resource("Sources", workspace_id=None))+ assert resource["endpoint"]["json"] == {"pageSize": 100}++ def test_paginated_endpoint_includes_workspace_id_when_set(self) -> None:+ resource = cast(dict[str, Any], get_resource("Sources", workspace_id=7))+ assert resource["endpoint"]["json"] == {"pageSize": 100, "workspaceId": 7}++ def test_collections_includes_workspace_id_as_query_param(self) -> None:+ resource = cast(dict[str, Any], get_resource("Collections", workspace_id=7))+ assert resource["endpoint"]["params"] == {"workspaceId": 7}++ def test_workspaces_endpoint_has_no_workspace_scoping(self) -> None:+ resource = cast(dict[str, Any], get_resource("Workspaces", workspace_id=7))+ assert "json" not in resource["endpoint"]+ assert "params" not in resource["endpoint"]++ def test_collections_carries_flatten_data_map(self) -> None:+ resource = cast(dict[str, Any], get_resource("Collections", workspace_id=None))+ assert resource["data_map"] is _flatten_collection+++class TestSinglePageEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_workspaces_single_get_request(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ calls = _wire(session, [_response({"workspaces": [{"id": 1, "name": "Default"}]})])++ rows = _rows(_build("Workspaces", manager))++ assert [r["id"] for r in rows] == [1]+ assert len(calls) == 1+ assert calls[0]["method"] == "GET"+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_metrics_uses_metrics_key(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(session, [_response({"metrics": [{"id": 5}]})])++ rows = _rows(_build("Metrics", manager))++ assert [r["id"] for r in rows] == [5]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_collections_flattens_nested_id(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(+ session,+ [_response({"collectionInfos": [{"collectionConfiguration": {"id": 9, "name": "Nightly"}}]})],+ )++ rows = _rows(_build("Collections", manager))++ assert rows[0]["id"] == 9+ assert rows[0]["name"] == "Nightly"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_client_bounds_every_request_with_a_timeout(self, MockSession: mock.MagicMock) -> None:+ # Without this a stalled connect or hung read on a customer-controlled host would pin an+ # import worker indefinitely.+ session = MockSession.return_value+ manager = _make_manager()+ _wire(session, [_response({"workspaces": [{"id": 1, "name": "Default"}]})])++ _rows(_build("Workspaces", manager))++ assert session.send.call_args.kwargs["timeout"] == REQUEST_TIMEOUT_SECONDS++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_client_never_follows_redirects(self, MockSession: mock.MagicMock) -> None:+ # A validated host could still 3xx a sync request to an internal address; refuse to+ # follow redirects on every sync request (SSRF defense-in-depth).+ session = MockSession.return_value+ manager = _make_manager()+ _wire(session, [_response({"workspaces": [{"id": 1, "name": "Default"}]})])++ _rows(_build("Workspaces", manager))++ assert session.send.call_args.kwargs["allow_redirects"] is False+++class TestCursorPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_pages_until_cursor_empty(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ calls = _wire(+ session,+ [+ _response({"sources": [{"id": 1}], "paginationInfo": {"nextCursor": "c1"}}),+ _response({"sources": [{"id": 2}], "paginationInfo": {"nextCursor": ""}}),+ ],+ )++ rows = _rows(_build("Sources", manager))++ assert [r["id"] for r in rows] == [1, 2]+ assert [c["method"] for c in calls] == ["POST", "POST"]+ assert calls[0]["json"] == {"pageSize": 100}+ assert calls[1]["json"] == {"pageSize": 100, "pageCursor": "c1"}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_issues_uses_singular_issue_key(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(session, [_response({"issue": [{"id": 3}], "paginationInfo": {"nextCursor": ""}})])++ rows = _rows(_build("Issues", manager))++ assert [r["id"] for r in rows] == [3]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_cursor_after_non_terminal_page(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(+ session,+ [+ _response({"tables": [{"id": 1}], "paginationInfo": {"nextCursor": "c1"}}),+ _response({"tables": [{"id": 2}], "paginationInfo": {"nextCursor": ""}}),+ ],+ )++ _rows(_build("Tables", manager))++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [BigeyeResumeConfig(next_cursor="c1")]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_single_terminal_page_saves_nothing(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager()+ _wire(session, [_response({"tables": [{"id": 1}], "paginationInfo": {"nextCursor": ""}})])++ _rows(_build("Tables", manager))++ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_seeds_cursor(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ manager = _make_manager(BigeyeResumeConfig(next_cursor="resumed"))+ calls = _wire(session, [_response({"tables": [{"id": 1}], "paginationInfo": {"nextCursor": ""}})])++ _rows(_build("Tables", manager))++ assert calls[0]["json"] == {"pageSize": 100, "pageCursor": "resumed"}+++class TestBigeyeSourceResponse:+ @pytest.mark.parametrize("endpoint", list(BIGEYE_ENDPOINTS.keys()))+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_primary_keys_match_settings(self, MockSession: mock.MagicMock, endpoint: str) -> None:+ MockSession.return_value.headers = {}+ response = _build(endpoint, _make_manager())+ assert response.name == endpoint+ assert response.primary_keys == [BIGEYE_ENDPOINTS[endpoint].primary_key]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_items_is_lazy(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ session.headers = {}+ _build("Workspaces", _make_manager())+ session.send.assert_not_called()++ def test_auth_header_carries_apikey_prefix(self) -> None:+ # Bigeye's auth header is `apikey <token>`, not the framework's default `Bearer <token>`.+ assert _auth_header_value("secret-token") == "apikey secret-token"+++class TestValidateCredentials:+ def _run(self, response: Any, **kwargs: Any) -> tuple[bool, str | None]:+ with mock.patch(BIGEYE_SESSION_PATCH) as factory:+ session = factory.return_value+ session.get.return_value = response+ return validate_credentials(api_key="key", host=None, workspace_id=None, **kwargs)++ def test_ok(self) -> None:+ valid, error = self._run(_response({"workspaces": []}, status_code=200))+ assert valid is True+ assert error is None++ def test_invalid_api_key(self) -> None:+ valid, error = self._run(_response({}, status_code=401))+ assert valid is False+ assert error == "Invalid Bigeye API key. Please check your key and try again."++ def test_forbidden(self) -> None:+ valid, error = self._run(_response({}, status_code=403))+ assert valid is False+ assert error is not None and "permission" in error++ def test_unexpected_status(self) -> None:+ valid, error = self._run(_response({}, status_code=500))+ assert valid is False+ assert error is not None and "500" in error++ def test_network_error_returns_message(self) -> None:+ with mock.patch(BIGEYE_SESSION_PATCH) as factory:+ factory.return_value.get.side_effect = requests.ConnectionError("boom")+ valid, error = validate_credentials(api_key="key", host=None, workspace_id=None)+ assert valid is False+ assert error is not None and "boom" in error++ def test_rejects_redirect_response(self) -> None:+ # A validated host that 3xx-redirects (potentially to an internal address) must be+ # rejected, not followed (SSRF).+ with mock.patch(BIGEYE_SESSION_PATCH) as factory:+ resp = _response({}, status_code=302)+ resp.headers["Location"] = "https://10.0.0.1/internal"+ factory.return_value.get.return_value = resp+ valid, error = validate_credentials(api_key="key", host=None, workspace_id=None)+ assert valid is False+ assert error == "That Bigeye host is not allowed."+ assert factory.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host_when_team_id_supplied(self) -> None:+ # When a team_id is supplied, a host resolving to an internal address is rejected before+ # any HTTP request is made (SSRF guard).+ with (+ mock.patch.object(bigeye_module, "_is_host_safe", return_value=(False, "internal address")),+ mock.patch(BIGEYE_SESSION_PATCH) as factory,+ ):+ valid, error = validate_credentials(api_key="key", host="10.0.0.1", workspace_id=None, team_id=99)++ assert valid is False+ assert error == "internal address"+ factory.return_value.get.assert_not_called()++ def test_custom_host_is_used(self) -> None:+ with mock.patch(BIGEYE_SESSION_PATCH) as factory:+ factory.return_value.get.return_value = _response({"workspaces": []}, status_code=200)+ validate_credentials(api_key="key", host="bigeye.internal.example.com", workspace_id=None)++ called_url = factory.return_value.get.call_args.args[0]+ assert called_url == "https://bigeye.internal.example.com/api/v1/workspaces"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/tests/test_bigeye_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/tests/test_bigeye_source.pynew file mode 100644index 000000000000..0d13fb4a8099--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigeye/tests/test_bigeye_source.py@@ -0,0 +1,149 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.bigeye import BigeyeResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.source import BigeyeSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bigeye import BigeyeSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "Workspaces",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestBigeyeSource:+ def setup_method(self) -> None:+ self.source = BigeyeSource()+ self.team_id = 123+ self.config = BigeyeSourceConfig(api_key="test-key", host=None, workspace_id=None)++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.BIGEYE++ def test_host_is_a_connection_host_field(self) -> None:+ # The stored API key is sent to the configured host, so retargeting it must re-require the key.+ assert self.source.connection_host_fields == ["host"]++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Bigeye"+ assert config.label == "Bigeye"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/bigeye.png"++ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert [f.name for f in fields] == ["api_key", "host", "workspace_id"]++ by_name = {f.name: f for f in fields}+ assert by_name["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert by_name["api_key"].secret is True+ assert by_name["api_key"].required is True+ assert by_name["host"].type == SourceFieldInputConfigType.TEXT+ assert by_name["host"].required is False+ assert by_name["workspace_id"].type == SourceFieldInputConfigType.NUMBER+ assert by_name["workspace_id"].required is False++ def test_no_unreleased_source_flag(self) -> None:+ # A finished source ships visible; unreleasedSource hides it from the wizard entirely.+ assert self.source.get_source_config.unreleasedSource is None++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ keys = self.source.get_non_retryable_errors()+ assert any(expected_key in k for k in keys)++ def test_get_schemas_all_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ # No Bigeye list endpoint exposes a server-side updated-since filter.+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Issues"])+ assert len(schemas) == 1+ assert schemas[0].name == "Issues"++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid", "expected_message"),+ [+ ((True, None), True, None),+ (+ (False, "Invalid Bigeye API key. Please check your key and try again."),+ False,+ "Invalid Bigeye API key. Please check your key and try again.",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.source.validate_bigeye_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ mock_return: tuple[bool, str | None],+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("test-key", None, None, self.team_id)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BigeyeResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bigeye.source.bigeye_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ config = BigeyeSourceConfig(api_key="test-key", host="bigeye.internal.example.com", workspace_id=7)+ inputs = _make_inputs(schema_name="Issues", team_id=99, job_id="job-xyz")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="test-key",+ host="bigeye.internal.example.com",+ workspace_id=7,+ endpoint="Issues",+ team_id=99,+ job_id="job-xyz",+ resumable_source_manager=manager,+ )++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ described = self.source.get_canonical_descriptions()+ assert set(described.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigeye.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigeye.pyindex 7e23ef8ffe51..0556a300173a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigeye.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bigeye.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass BigeyeSourceConfig(config.Config):- pass+ api_key: str+ workspace_id: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)+ host: str | None = None