: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
refactor(warehouse-sources): split external data source view (#98377)
Paul D'Ambra47c86593c1b5
diff --git a/.semgrep/rules/devex/api-response-must-match-schema.yaml b/.semgrep/rules/devex/api-response-must-match-schema.yamlindex 6cc246d7f719..102e837386b5 100644--- a/.semgrep/rules/devex/api-response-must-match-schema.yaml+++ b/.semgrep/rules/devex/api-response-must-match-schema.yaml@@ -49,7 +49,7 @@ rules:# data payloads. Match the dict's *first key* so we don't accidentally# exempt larger payloads that happen to contain one of these names.# `(?:data=)?` covers both `Response({...})` and `Response(data={...})`.- - pattern-not-regex: 'Response\(\s*(?:data=)?\{\s*"(detail|error|errors|message|status|success|ok|results|count|next|previous)"\s*:'+ - pattern-not-regex: 'Response\(\s*(?:status\s*=\s*[^,)]+,\s*)?(?:data\s*=\s*)?\{\s*"(detail|error|errors|message|status|success|ok|results|count|next|previous)"\s*:'metadata:category: best-practicesubcategory:diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex a9fd357900cc..57fde4d1024f 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -52,7 +52,7 @@ from products.warehouse_sources.backend.facade.types import (DataWarehouseTableFormat,ExternalDataSourceAccessMethod,)-from products.warehouse_sources.backend.presentation.views.external_data_source import (+from products.warehouse_sources.backend.presentation.views.external_data_source.source_setup import (SimpleExternalDataSourceSerializers,)diff --git a/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py b/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.pyindex 2200ff5ebced..4be712ce030f 100644--- a/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py+++ b/products/data_warehouse/backend/tests/api/test_postgres_warehouse_migration.py@@ -28,7 +28,7 @@ def _stub_source_security_gate(source_mock) -> None:class TestPostgresWarehouseMigration(APIBaseTest):- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_qualifies_legacy_warehouse_rows_in_place(self, mock_get_source):# A pre-PR warehouse Postgres source had `schema=public` on the source config and# `ExternalDataSchema.name="auth_group"` (no schema prefix). After this PR, discovery@@ -102,7 +102,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):).values_list("name", flat=True)assert list(live_schemas) == ["public.auth_group"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_idempotent_on_legacy_warehouse_rows(self, mock_get_source):# Calling refresh_schemas twice on a legacy row should be a no-op on the second call —# name stays put, schema_metadata stays put, no thrash of updated_at.@@ -157,7 +157,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):assert metadata.get("source_table_name") == "auth_group"assert schema.s3_folder_name == "auth_group"- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_refreshes_legacy_warehouse_metadata_when_columns_change(self, mock_get_source):# available_columns must keep up with upstream changes for legacy unqualified rows.# Without resolving the row by source location, reconcile_postgres_schemas would only@@ -221,7 +221,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):column_names = [c["name"] for c in metadata_columns]assert column_names == ["id", "new_column"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_writes_metadata_for_new_other_schema_table_after_schema_cleared(self, mock_get_source):# Scenario reported by users:# 1. Source created on master with `job_inputs={schema: "public"}` — limits sync to the@@ -302,7 +302,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):)assert new_metadata.get("source_table_name") == "example_table"- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_clearing_postgres_schema_pins_legacy_rows_to_old_default_schema(self, mock_get_source):# Repro for "lost data after clearing schema". Source had schema=poblic, legacy unqualified# rows were synced from poblic.<name>. When user clears the schema field, the next refresh@@ -388,7 +388,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):team_id=self.team.pk, source_id=source.pk, name="example_table", deleted=False).exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_clearing_postgres_schema_drops_duplicate_qualified_row(self, mock_get_source):# A prior refresh (before this migration landed) might have created `poblic.example_table`# as a separate row. When the user clears the schema, the legacy unqualified row gets@@ -481,7 +481,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):orphan.refresh_from_db()assert orphan.deleted is True- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_persists_detected_primary_key_for_cdc(self, mock_get_source):# A table added after source creation is discovered via refresh. Its detected primary key# must be persisted to sync_type_config.primary_key_columns so it can later be switched to@@ -526,7 +526,7 @@ class TestPostgresWarehouseMigration(APIBaseTest):assert schema.sync_type_config.get("primary_key_columns") == ["id"]assert schema.primary_key_columns == ["id"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_does_not_clobber_existing_primary_key(self, mock_get_source):# A user-set / previously-stored PK must survive refresh even if discovery detects a# different one — the explicit choice wins.diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pydeleted file mode 100644index 34b1bd37ff19..000000000000--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ /dev/null@@ -1,5767 +0,0 @@-from __future__ import annotations--import uuid-import dataclasses-from collections.abc import Callable, Iterable, Mapping-from datetime import UTC, datetime, timedelta-from typing import Any, cast-from urllib.parse import quote--from django.conf import settings-from django.core.cache import cache-from django.core.exceptions import ValidationError as DjangoValidationError-from django.db import connection, transaction-from django.db.models import Prefetch, Q, QuerySet-from django.utils import timezone-from django.utils.cache import patch_cache_control--import structlog-import temporalio-from dateutil import parser-from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_field-from openai import APIConnectionError-from opentelemetry import trace-from psycopg import OperationalError-from rest_framework import filters, serializers, status, viewsets-from rest_framework.exceptions import APIException, PermissionDenied, ValidationError-from rest_framework.permissions import IsAuthenticated-from rest_framework.request import Request-from rest_framework.response import Response-from sshtunnel import BaseSSHTunnelForwarderError--from posthog.hogql.database.database import Database-from posthog.hogql.direct_sql.capability import direct_capable_source_types--from posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.utils import action-from posthog.dataclasses import frozen-from posthog.event_usage import EventSource, get_event_source, is_wizard_self_driving_program, report_user_action-from posthog.exceptions_capture import capture_exception-from posthog.models.integration import Integration-from posthog.models.user import User-from posthog.permissions import (- AccessControlPermission,- APIScopePermission,- TeamMemberAccessPermission,- TeamMemberAdminManagementPermission,- is_service_auth,-)-from posthog.rate_limit import (- CustomSourceAIBuilderBurstThrottle,- CustomSourceAIBuilderDailyThrottle,- CustomSourceAIBuilderSustainedThrottle,-)--from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource-from products.access_control.backend.presentation.access_control import (- AccessControlViewSetMixin,- UserAccessControlSerializerMixin,-)-from products.cdp.backend.facade.api import HogFunctionSerializer-from products.cdp.backend.facade.models import HogFunction-from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet-from products.data_warehouse.backend.facade.api import (- DirectQueryEngine,- apply_on_refresh as apply_sql_warehouse_refresh_migration,- apply_on_schema_clear as apply_sql_warehouse_schema_clear_migration,- bulk_create_external_data_job_schedules,- bulk_delete_external_data_schedules,- cancel_external_data_workflow,- create_and_register_webhook,- delete_cdc_extraction_schedule,- delete_discover_schemas_schedule,- delete_external_data_schedule,- delete_webhook_and_hog_function,- detect_schema_clear_transition as detect_sql_schema_clear_transition,- ensure_cdc_slot_cleanup_schedule,- get_direct_query_engine,- get_namespaced_resource_adapter,- get_or_create_webhook_hog_function,- get_postgres_source_location,- get_webhook_url,- is_any_external_data_schema_paused,- is_cdc_enabled_for_team,- is_cdc_extraction_schedule_paused,- is_custom_source_ai_builder_enabled_for_team,- is_multi_schema_capable_sql_source,- source_namespace_is_blank,- sync_cdc_extraction_schedule,- sync_discover_schemas_schedule,- sync_external_data_job_workflow,- trigger_external_data_source_workflow,- unpause_cdc_extraction_schedule,-)-from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfig-from products.revenue_analytics.backend.facade.api import ensure_person_join, remove_person_join-from products.warehouse_sources.backend.facade.api import validate_source_prefix-from products.warehouse_sources.backend.facade.models import (- MANAGED_WAREHOUSE_SOURCE_PREFIX,- DataWarehouseTable,- ExternalDataDestination,- ExternalDataJob,- ExternalDataSchema,- ExternalDataSource,- ExternalDataSourceDestination,- PendingSourceCredential,- auto_enable_new_schemas,- latest_completed_job_prefetch,- sync_old_schemas_with_new_schemas,- update_sync_type_config_keys,-)-from products.warehouse_sources.backend.facade.source_config import (- SourceConfigMapResponse,- SourceFieldFileUploadConfig,- SourceFieldInputConfig,- SourceFieldInputConfigType,- SourceFieldOauthAccountSelectConfig,- SourceFieldOauthConfig,- SourceFieldSelectConfig,- SourceFieldSSHTunnelConfig,- SourceFieldSwitchGroupConfig,-)-from products.warehouse_sources.backend.facade.source_management import (- DATABASE_HOST_NOT_ALLOWED_GUIDANCE,- DEFAULT_LAG_CRITICAL_THRESHOLD_MB,- DEFAULT_LAG_WARNING_THRESHOLD_MB,- PREVIEW_DEFAULT_ROWS,- PREVIEW_MAX_ROWS,- AnySource,- CDCRepairError,- CDCRepairInProgress,- CDCSourceAdapter,- ClickHouseSource,- Config,- CustomSource,- CustomSourceConfig,- DocsFetchError,- ExternalWebhookInfo,- FieldType,- HostNotAllowedError,- IntegrationAccountListingError,- MySQLSource,- OAuthMixin,- PostgresSource,- RowFilterValidationError,- SourceRegistry,- SourceSchema,- SQLSource,- SSLRequiredError,- TemporaryHostResolutionError,- WebhookSource,- build_default_schemas,- build_default_sync_settings,- cdc_pg_connection,- draft_manifest_sync,- fetch_docs_text,- filter_dwh_columns_by_enabled_columns,- filter_integration_accounts,- get_cdc_adapter,- get_primary_key_columns,- new_source_requires_ssl,- purge_buffer_prefix,- repair_cdc_source,- source_requires_ssl,- source_type_supports_cdc,- sql_schema_metadata,- validate_and_coerce_row_filters,-)-from products.warehouse_sources.backend.facade.types import (- DataWarehouseManagedViewSetKind,- ExternalDataSourceType,- ManagedWarehouseSQLMode,-)-from products.warehouse_sources.backend.presentation.views.destination_links import (- DestinationLinkSerializer,- SourceDestinationsSerializer,- set_source_destinations,-)-from products.warehouse_sources.backend.presentation.views.external_data_schema import (- ExternalDataSchemaListSerializer,- ExternalDataSchemaSerializer,- RowFiltersField,- SimpleExternalDataSchemaSerializer,- source_supports_column_selection,- unsupported_row_filter_reason,-)-from products.warehouse_sources.backend.presentation.views.public_source_configs import build_source_configs-from products.warehouse_sources.backend.presentation.views.source_api_versions import (- ExternalDataSourceApiVersionDeprecationSerializer,- api_version_deprecation_payload,-)--logger = structlog.get_logger(__name__)--REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE = "Could not fetch schemas from source."-RESERVED_SOURCE_NAME_MESSAGE = "This source name is reserved by PostHog."-INVALID_CREDENTIALS_FALLBACK_MESSAGE = (- "We couldn't validate those credentials. Check they're correct and have the required access, then try again."-)---def _source_unavailable_message(source_type: str) -> str:- # A source with no schema discovery is an unreleased scaffold the UI normally hides. Tell the- # user it isn't ready rather than exposing the internal "schema discovery" wording.- return (- f"The {source_type} source isn't available to connect yet. "- "Choose a different source, or contact support if you were expecting it."- )---def _canonical_legacy_managed_warehouse_source(- queryset: QuerySet[ExternalDataSource],-) -> ExternalDataSource | None:- candidates = (- queryset.select_related(None)- .filter(ExternalDataSource.legacy_managed_warehouse_q())- .only(- "id",- "team_id",- "created_at",- "prefix",- "connection_metadata",- "source_type",- "access_method",- "direct_query_enabled",- "job_inputs",- )- .order_by("-created_at")- )- return next(- (source for source in candidates if source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL),- None,- )---def _hide_noncanonical_managed_warehouse_sources(- queryset: QuerySet[ExternalDataSource], canonical_source: ExternalDataSource | None-) -> QuerySet[ExternalDataSource]:- hidden_sources = Q(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)- if canonical_source is not None:- hidden_sources &= ~Q(pk=canonical_source.pk)- return queryset.exclude(hidden_sources)---# Failures to reach the source database that only the customer can fix. Handlers return them as a-# 400 without capturing, so they stay out of error tracking.-_EXPECTED_CONNECTION_ERRORS = (- OperationalError,- BaseSSHTunnelForwarderError,- SSLRequiredError,- HostNotAllowedError,- TemporaryHostResolutionError,-)--REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {- "timeout": "Connection timed out while fetching schemas from the source.",- "timed out": "Connection timed out while fetching schemas from the source.",- "connection refused": "Could not connect to the source. Check the host, port, and network access.",- "could not connect": "Could not connect to the source. Check the host, port, and network access.",- "could not translate host name": "Could not resolve the source host.",- "name or service not known": "Could not resolve the source host.",- "network is unreachable": "Could not reach the source network.",- "no route to host": "Could not reach the source host.",- "access denied": "Could not authenticate with the source. Check the connection credentials.",- "authentication failed": "Could not authenticate with the source. Check the connection credentials.",- "password authentication failed": "Could not authenticate with the source. Check the connection credentials.",- "unauthorized": "Could not authenticate with the source. Check the connection credentials.",- "forbidden": "The source credentials do not have permission to fetch schemas.",- "ssl/tls connection is required": "SSL/TLS is required to connect to the source.",- "could not establish session to ssh gateway": "Could not establish an SSH tunnel to the source.",- # Raised by the connect-time host check of every SQL source; the map is matched on lowercased text.- "database host not allowed": DATABASE_HOST_NOT_ALLOWED_GUIDANCE,- "temporary failure resolving": "Could not resolve the source host right now. Try again in a moment.",-}---def _exception_text(error: Exception) -> str:- message = " ".join(str(arg) for arg in error.args if arg is not None) or str(error)- return f"{type(error).__name__}: {message}"---def _classify_refresh_schemas_error(source: AnySource | None, error: Exception) -> tuple[str, bool]:- error_text = _exception_text(error)- normalized_error_text = error_text.lower()- matched_source_error = False-- if source is not None:- for pattern, friendly_message in source.get_non_retryable_errors().items():- if pattern and pattern.lower() in normalized_error_text:- if friendly_message:- return friendly_message, True- matched_source_error = True-- for pattern, friendly_message in REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES.items():- if pattern in normalized_error_text:- return friendly_message, True-- if matched_source_error:- return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, True-- return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, False---def _credentials_validation_failed(source: AnySource, team_id: int, error: Exception) -> tuple[bool, str | None]:- """Fallback result for an *unexpected* exception raised by a source's credential probe.-- Sources are expected to catch their own errors and return ``(False, message)``. One that raises- instead would 500 the create/update request and show someone mid-onboarding an opaque server- error, so capture it for us and hand back an actionable message — the same treatment schema- discovery already gives an unexpected error just below the credential check."""- capture_exception(error, {"source_type": str(source.source_type), "team_id": team_id})- return False, INVALID_CREDENTIALS_FALLBACK_MESSAGE---def get_sensitive_field_names(fields: list[FieldType]) -> set[str]:- """Extract field names that contain sensitive data from a source config's fields."""- sensitive: set[str] = set()- for field in fields:- if isinstance(field, SourceFieldInputConfig) and (- field.type == SourceFieldInputConfigType.PASSWORD or field.secret- ):- sensitive.add(field.name)- elif isinstance(field, SourceFieldFileUploadConfig):- sensitive.add(field.name)- elif isinstance(field, SourceFieldSwitchGroupConfig):- sensitive.update(get_sensitive_field_names(field.fields))- elif isinstance(field, SourceFieldSelectConfig):- for option in field.options:- if option.fields:- sensitive.update(get_sensitive_field_names(option.fields))- return sensitive---def get_oauth_integration_kinds(fields: list[FieldType]) -> set[str]:- """The integration kinds a source connects with, declared by its `oauth` fields (`kind`) and its- `oauth-account-select` fields (`integrationKind`). Every OAuth account listing is served by one- endpoint that takes an integration id from the caller, so this is what the endpoint checks that id- against — a Google integration id must not be able to route its token into the LinkedIn Ads client- just because both rows belong to the caller's team.-- Both field types are read because a source can list accounts without rendering a picker: GitHub- serves repositories to its own component off a plain `oauth` field."""- kinds: set[str] = set()- for field in fields:- if isinstance(field, SourceFieldOauthAccountSelectConfig):- kinds.add(field.integrationKind)- elif isinstance(field, SourceFieldOauthConfig):- kinds.add(field.kind)- elif isinstance(field, SourceFieldSwitchGroupConfig):- kinds.update(get_oauth_integration_kinds(field.fields))- elif isinstance(field, SourceFieldSelectConfig):- for option in field.options:- if option.fields:- kinds.update(get_oauth_integration_kinds(option.fields))- return kinds---def _name_variants(name: str) -> tuple[str, ...]:- """The spellings a declared field name can be stored under, declared spelling first.-- Source field names may use hyphens (e.g. "temporary-dataset") while- dataclasses.asdict() persists the snake_case field name ("temporary_dataset").- """- normalised = name.replace("-", "_")- return (name,) if normalised == name else (name, normalised)---def _add_name_variants(target: set[str], name: str) -> None:- """Add a field name and its underscore variant to a set.-- We need to recognise both forms when classifying persisted job_inputs.- """- target.update(_name_variants(name))---def _stored_key(data: Mapping[str, Any], name: str) -> str | None:- """The key `data` holds a declared field under, or None when it holds neither spelling.-- Prefers the declared spelling when both are present, matching how config parsing- resolves the alias.- """- return next((key for key in _name_variants(name) if key in data), None)---def _stored_value(data: Mapping[str, Any], name: str) -> Any:- """The value `data` holds for a declared field under either spelling."""- key = _stored_key(data, name)- return data[key] if key is not None else None---@frozen-class DeclaredFieldNames:- """Declared field names that need special handling when reading or merging job_inputs.-- `hyphenated` are names the source declares with a hyphen. `dataclasses.asdict()` persists- the Python attribute name instead, so stored configs can hold either spelling.- `switch_groups` are switch-group container names, whose stored value is a nested dict.- """-- hyphenated: set[str]- switch_groups: set[str]---def get_declared_field_names(fields: list[FieldType]) -> DeclaredFieldNames:- """Collect hyphenated and switch-group field names, flattened across all nesting levels."""- hyphenated: set[str] = set()- switch_groups: set[str] = set()-- for field in fields:- if "-" in field.name:- hyphenated.add(field.name)- if isinstance(field, SourceFieldSwitchGroupConfig):- switch_groups.add(field.name)- nested = get_declared_field_names(field.fields)- hyphenated.update(nested.hyphenated)- switch_groups.update(nested.switch_groups)- elif isinstance(field, SourceFieldSelectConfig):- for option in field.options:- if option.fields:- nested = get_declared_field_names(option.fields)- hyphenated.update(nested.hyphenated)- switch_groups.update(nested.switch_groups)-- return DeclaredFieldNames(hyphenated=hyphenated, switch_groups=switch_groups)---def restore_declared_field_names(data: dict, hyphenated: set[str]) -> dict:- """Return a copy of data re-keyed to the names the source config declares.-- A hyphenated field round-trips through `dataclasses.asdict()`, which writes the Python- attribute name ("temporary_dataset") rather than the declared one ("temporary-dataset").- Clients key off the declared name, so restore it. When both spellings are present the- declared one wins, matching how config parsing prefers the alias.- """- if not hyphenated:- return data-- variants = {name.replace("-", "_"): name for name in hyphenated}- result: dict = {}- for key, value in data.items():- declared = variants.get(key)- if declared is not None:- if declared in data:- continue- key = declared- if isinstance(value, dict):- value = restore_declared_field_names(value, hyphenated)- result[key] = value- return result---@frozen-class FieldSensitivitySplit:- nonsensitive: set[str]- sensitive: set[str]---def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> FieldSensitivitySplit:- """Classify source config field names as nonsensitive or sensitive.-- Returns the field-name sets flattened across all nesting levels.- """- nonsensitive: set[str] = set()- sensitive: set[str] = set()-- for field in fields:- if isinstance(field, SourceFieldInputConfig):- if field.type == SourceFieldInputConfigType.PASSWORD or field.secret:- _add_name_variants(sensitive, field.name)- else:- _add_name_variants(nonsensitive, field.name)- elif isinstance(field, SourceFieldFileUploadConfig):- _add_name_variants(sensitive, field.name)- elif isinstance(field, SourceFieldSelectConfig):- _add_name_variants(nonsensitive, field.name)- for option in field.options:- if option.fields:- nested = get_nonsensitive_and_sensitive_field_names(option.fields)- nonsensitive.update(nested.nonsensitive)- sensitive.update(nested.sensitive)- elif isinstance(field, SourceFieldSwitchGroupConfig):- _add_name_variants(nonsensitive, field.name)- nested = get_nonsensitive_and_sensitive_field_names(field.fields)- nonsensitive.update(nested.nonsensitive)- sensitive.update(nested.sensitive)- elif isinstance(field, SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig):- # The selected account/property is a plain identifier (e.g. Bing Ads account_id,- # GSC site_url), not a secret — keep it so the form can prefill on edit.- _add_name_variants(nonsensitive, field.name)- elif isinstance(field, SourceFieldSSHTunnelConfig):- _add_name_variants(nonsensitive, field.name)- # SSH tunnel has a known nested structure not declared in the field tree.- # "auth"/"auth_type" are container keys for SSHTunnelAuthConfig.- nonsensitive.update({"host", "port", "username", "auth", "auth_type", "require_tls"})- sensitive.update({"password", "passphrase", "private_key"})-- return FieldSensitivitySplit(nonsensitive=nonsensitive, sensitive=sensitive)---# Config metadata keys that are always safe to include in nested dicts-_CONFIG_META_KEYS = {"selection", "enabled"}--# CDC config lives in job_inputs but isn't part of any source's user-facing form field-# tree, so it would otherwise be stripped from API reads as "unknown". None of these are-# secrets — they're operational config the Configuration page needs to render CDC state.-_CDC_EXPOSED_JOB_INPUT_KEYS = {- "cdc_enabled",- "cdc_management_mode",- "cdc_slot_name",- "cdc_publication_name",- "cdc_auto_drop_slot",- "cdc_lag_warning_threshold_mb",- "cdc_lag_critical_threshold_mb",- "cdc_consistent_point",- # Set by migrate_cdc_source_to_buffered, never by the API. Losing it on an unrelated PATCH- # would resume legacy delivery from an advanced slot and strand the unread buffer.- "cdc_ingest_mode",-}---def strip_sensitive_from_dict(data: dict, nonsensitive: set[str], sensitive: set[str]) -> dict:- """Return a copy of data with sensitive and unknown keys removed.-- Keys in the nonsensitive set or config metadata keys are kept.- Keys in the sensitive set or not in any known set are stripped.- Nested dicts are processed recursively.- """- result: dict = {}- for key, value in data.items():- if key in sensitive:- continue- if key not in nonsensitive and key not in _CONFIG_META_KEYS:- continue- if isinstance(value, dict):- result[key] = strip_sensitive_from_dict(value, nonsensitive, sensitive)- else:- result[key] = value- return result---# Fields whose change could redirect the database connection to a different server-# (and therefore exfiltrate credentials via a poisoned SSH tunnel — VERIA-311).-_SSH_TUNNEL_CONNECTION_FIELDS = ("enabled", "host", "port")--# Top-level job_input fields that name the connection target. Changing any of them-# repoints the source at a different server, so preserved credentials must not be-# reused without re-entry (e.g. ServiceNow's `instance_url` could otherwise be swapped-# to an attacker host that then receives the stored API key / password — VERIA-311).-_CONNECTION_TARGET_FIELDS = ("host", "instance_url")---def _coerce_connection_target(value: Any) -> str:- """Normalize a connection-target value for comparison.-- Scalars are coerced to strings to ignore type drift between stored values- (often strings) and JSON-parsed input (bools/ints). Only `None` collapses to ""- — `or ""` would also swallow falsy-but-meaningful values like `False` and 0,- making stored "False" falsely diverge from JSON `false`.- """- return "" if value is None else str(value)---def connection_target_changed(existing: Any, incoming: Any) -> bool:- """True if a named connection-target field actually moved to a different target.-- An unset field and a blank one name the same (absent) target, so collapsing them keeps the- gate off an edit that changes nothing: the edit form submits a blank for every declared field- the stored source never had, and treating that as a retarget blocks the whole form behind a- credential re-entry that does not apply.- """- return _coerce_connection_target(existing) != _coerce_connection_target(incoming)---def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:- """True if the SSH tunnel's connection target (enabled/host/port) changed."""- existing = existing if isinstance(existing, dict) else {}- incoming = incoming if isinstance(incoming, dict) else {}-- return any(connection_target_changed(existing.get(key), incoming.get(key)) for key in _SSH_TUNNEL_CONNECTION_FIELDS)---# Nested containers that keep their secrets one level down, not at the top level: the-# SourceFieldSelectConfig ones (Stripe `auth_method`, Snowflake `auth_type`, ServiceNow-# `auth_method`) key their selected branch as `selection`; the SourceFieldSwitchGroupConfig-# one (Billomat's `registered_app`) keys it as `enabled` instead, but the same carried-over--# secret check below applies either way.-_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type", "registered_app")--# Secrets the edit form can never re-supply (parsed into the individual fields on create, then-# stripped from API reads and hidden in the edit form), so gating credential re-entry on them would-# permanently block host changes. Excluded from the gate but still preserved by the merge: MongoDB-# connects via `connection_string`, while SQL sources use the individual fields and gate `password`.-_CREATION_ONLY_SECRET_FIELDS = frozenset({"connection_string"})---def has_preserved_credentials(- existing: dict[str, Any],- incoming: dict[str, Any],- sensitive_fields: set[str],- nested_containers: Iterable[str] = _NESTED_AUTH_CONTAINERS,-) -> bool:- """True if any stored secret would be reused because the update didn't re-supply it.-- Checks both top-level secret fields and the nested containers where sources like- ServiceNow, Stripe and Snowflake keep their credentials. Used to force credential- re-entry when the connection target changes, so a redirected host can't receive a- preserved secret. A secret only counts as preserved when it would survive the merge:- an absent container carries the whole existing block over, a same-selection container- preserves any field the update omits, and a selection switch replaces the block wholesale.-- Switch groups merge the same way, so callers pass their names too. A switch group carries- no `selection`, which reads as unchanged and lands on the omitted-field check — the branch- that matches how the merge treats them. A group declared with a hyphen can be stored under- either spelling, so containers are resolved the same way the merge resolves them.- """- if any(existing.get(key) and not incoming.get(key) for key in sensitive_fields):- return True-- for container_key in nested_containers:- existing_container = _stored_value(existing, container_key)- if not isinstance(existing_container, dict):- continue- incoming_container = _stored_value(incoming, container_key)- if not isinstance(incoming_container, dict):- # Container not re-supplied — the existing secrets carry over wholesale.- if any(existing_container.get(key) for key in sensitive_fields):- return True- continue- if existing_container.get("selection") != incoming_container.get("selection"):- continue- if any(existing_container.get(key) and not incoming_container.get(key) for key in sensitive_fields):- return True-- return False---def get_direct_connection_metadata(- *,- source_impl: Any,- source_config: Config,- team_id: int,- source_model: ExternalDataSource | None = None,- fallback: dict[str, Any] | None = None,-) -> dict[str, Any]:- metadata_fetcher = getattr(source_impl, "get_connection_metadata", None)- if not callable(metadata_fetcher):- return fallback or {}-- require_ssl = source_model is not None and source_requires_ssl(source_model, source_config)-- try:- metadata = metadata_fetcher(source_config, team_id, require_ssl=require_ssl)- except Exception as error:- # Connection metadata is best-effort — we fall back below regardless. An expected- # user/upstream connection failure (unreachable or misconfigured host, refused connection,- # bad credentials) is the customer's to fix and is already surfaced by credential- # validation, so don't capture it as error-tracking noise. Mirrors `refresh_schemas`.- _, is_expected_source_error = _classify_refresh_schemas_error(source_impl, error)- if not is_expected_source_error:- capture_exception(error)- return fallback or {}-- return metadata if isinstance(metadata, dict) else (fallback or {})---def get_postgres_source_table_location(- *,- schema_name: str,- source_schema: SourceSchema | None,- default_schema: str | None,-) -> tuple[str | None, str, str]:- return get_postgres_source_location(- schema_name=schema_name,- schema_metadata={- "source_catalog": source_schema.source_catalog if source_schema else None,- "source_schema": source_schema.source_schema if source_schema else None,- "source_table_name": source_schema.source_table_name if source_schema else None,- },- default_schema=default_schema,- )---DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, Redshift, ClickHouse, MotherDuck, and Trino sources."-# Engines surfaced on a direct connection's `connection_metadata.engine` (duckdb backs direct Postgres).-DIRECT_CONNECTION_ENGINE_CHOICES = [- "duckdb",- "postgres",- "mysql",- "snowflake",- "redshift",- "clickhouse",- "motherduck",- "trino",-]---def count_active_sources(team_id: int, source_type: str) -> int:- return ExternalDataSource.objects.filter(team_id=team_id, source_type=source_type).exclude(deleted=True).count()---def _refresh_name_substitutions(- engine: DirectQueryEngine | None, *, source: ExternalDataSource, source_schemas: list[Any], team_id: int-) -> dict[str, str]:- """Legacy-row name remapping applied before schema sync on refresh. The engine adapter's- remapping wins when it has one (Postgres's bespoke dedup — an empty dict still counts as- "handled" and suppresses the fallback); otherwise a multi-schema-capable SQL source with a- blank namespace gets the generic migration. Neither applies to any other source."""- if engine is not None:- engine_subs = engine.refresh_name_substitutions(source=source, source_schemas=source_schemas, team_id=team_id)- if engine_subs is not None:- return engine_subs- if source_namespace_is_blank(source) and is_multi_schema_capable_sql_source(source.source_type):- return apply_sql_warehouse_refresh_migration(source=source, team_id=team_id)- return {}---class ExternalDataSourceRevenueAnalyticsConfigSerializer(serializers.ModelSerializer):- class Meta:- model = ExternalDataSourceRevenueAnalyticsConfig- fields = ["enabled", "include_invoiceless_charges"]---class ExternalDataSourceConnectionMetadataSerializer(serializers.Serializer):- database = serializers.CharField(- read_only=True,- required=False,- allow_null=True,- help_text="Database name discovered for a direct connection.",- )- version = serializers.CharField(- read_only=True,- required=False,- allow_null=True,- help_text="Database version string reported by the direct connection.",- )- engine = serializers.ChoiceField(- read_only=True,- required=False,- allow_null=True,- choices=DIRECT_CONNECTION_ENGINE_CHOICES,- help_text="Backend engine detected for the direct connection.",- )- function_source = serializers.CharField(- read_only=True,- required=False,- allow_null=True,- help_text="System catalog or function source used to discover supported functions.",- )- available_functions = serializers.ListField(- child=serializers.CharField(),- read_only=True,- required=False,- help_text="Functions discovered as available on the direct connection.",- )---class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):- engine = serializers.ChoiceField(- source="connection_metadata.engine",- read_only=True,- allow_null=True,- choices=DIRECT_CONNECTION_ENGINE_CHOICES,- help_text="Backend engine detected for the direct connection.",- )- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- read_only=True,- help_text="The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').",- )- access_method = serializers.ChoiceField(- choices=ExternalDataSource.AccessMethod.choices,- read_only=True,- help_text="'direct' for pure live-query sources; 'warehouse' for synced sources with direct query enabled.",- )- supports_hogql = serializers.SerializerMethodField(- help_text="Whether HogQL queries compile for this connection. When false, only raw SQL (sendRawQuery) works.",- )- is_builtin_managed_warehouse = serializers.SerializerMethodField(- help_text="Whether this option is the built-in PostHog managed warehouse connection.",- )- description = serializers.CharField(- read_only=True,- allow_null=True,- help_text="User-set description of the source, shown as its display name in the connection picker when set.",- )-- @extend_schema_field(serializers.BooleanField())- def get_supports_hogql(self, source: ExternalDataSource) -> bool:- # Function-local: keeps the direct-SQL driver imports off the django.setup() path.- from posthog.hogql.direct_sql.capability import direct_supports_hogql # noqa: PLC0415-- return direct_supports_hogql(source)-- @extend_schema_field(serializers.BooleanField())- def get_is_builtin_managed_warehouse(self, source: ExternalDataSource) -> bool:- return source.pk == self.context.get("builtin_managed_warehouse_source_id")-- class Meta:- model = ExternalDataSource- fields = [- "id",- "prefix",- "engine",- "source_type",- "access_method",- "supports_hogql",- "is_builtin_managed_warehouse",- "description",- ]- read_only_fields = fields---class DirectConnectionSourceOptionSerializer(serializers.Serializer):- """A source type that can be added as a direct (live-query) connection, with display metadata."""-- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- read_only=True,- help_text="The source type to start a direct-connection setup for (e.g. 'Postgres', 'ClickHouse').",- )- label = serializers.CharField( # type: ignore[assignment] # field name intentionally shadows Field.label- read_only=True,- help_text="Human-readable name to show in the picker (falls back to the source type).",- )- icon_path = serializers.CharField(- read_only=True,- allow_null=True,- help_text="Path to the source's icon asset, or null when the source ships no icon.",- )---class ExternalDataSourceBulkUpdateSchemaSerializer(serializers.Serializer):- id = serializers.UUIDField(help_text="Schema identifier to update.")- should_sync = serializers.BooleanField(required=False, help_text="Whether the schema should be queryable/synced.")- sync_type = serializers.ChoiceField(- required=False,- allow_null=True,- choices=ExternalDataSchema.SyncType.choices,- help_text="Requested sync mode for the schema (incremental, full_refresh, append, cdc, or xmin).",- )- incremental_field = serializers.CharField(- required=False,- allow_null=True,- help_text="Incremental cursor field for incremental or append syncs.",- )- incremental_field_type = serializers.CharField(- required=False,- allow_null=True,- help_text="Type of the incremental cursor field.",- )- sync_frequency = serializers.CharField(- required=False,- allow_null=True,- help_text="Human-readable sync frequency value.",- )- sync_time_of_day = serializers.TimeField(- required=False,- allow_null=True,- help_text="UTC anchor time for scheduled syncs.",- )- primary_key_columns = serializers.ListField(- child=serializers.CharField(),- required=False,- allow_null=True,- help_text="Column names for primary key deduplication.",- )- cdc_table_mode = serializers.ChoiceField(- required=False,- allow_null=True,- choices=["consolidated", "cdc_only", "both"],- help_text="How CDC-backed tables should be exposed.",- )- enabled_columns = serializers.ListField(- child=serializers.CharField(),- required=False,- allow_null=True,- allow_empty=True,- help_text="Columns to sync. Null means sync all columns.",- )- row_filters = RowFiltersField(- required=False,- allow_null=True,- help_text="Row-filter predicates ANDed onto the source query. Null/empty means sync all rows.",- )- apply_sync_defaults = serializers.BooleanField(- required=False,- help_text=(- "When true and the schema has no sync method configured yet (and this update does not set "- "one), discover the table on the source and fill in default sync settings: incremental sync "- "with an auto-selected tracking column where supported, otherwise append, otherwise full "- "refresh. Ignored for schemas that already have a sync method."- ),- )---class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):- schemas = ExternalDataSourceBulkUpdateSchemaSerializer(- many=True,- allow_empty=False,- help_text="Schema updates to apply in a single batch.",- )-- # The endpoint is a PATCH, so the schema generator marks every field optional. The body is a- # batch command that always needs `schemas`, and the generated types and MCP tool must say so.- @property- def partial(self) -> bool:- return False-- @partial.setter- def partial(self, _value: bool) -> None:- pass---def _validation_error_message(error: ValidationError) -> str:- # DRF normalizes ValidationError.detail to a list or dict (never a bare string).- detail = error.detail- if isinstance(detail, dict):- return " ".join(f"{field}: {value}" for field, value in detail.items())- return " ".join(str(item) for item in detail)---class BulkSchemaSaveError(APIException):- default_code = "bulk_schema_save_failed"-- def __init__(self, failures: dict[str, tuple[str, str]], *, only_validation_errors: bool) -> None:- # Pure input problems are the caller's to fix (400). A database/infra error is ours and is- # retryable (503); treat a mix as a server problem so it surfaces as retryable.- self.status_code = (- status.HTTP_400_BAD_REQUEST if only_validation_errors else status.HTTP_503_SERVICE_UNAVAILABLE- )- reasons = "; ".join(f"{name} ({reason})" for name, reason in failures.values())- super().__init__(- detail=(- f"These schemas in the batch could not be saved: {reasons}. "- "Any other schemas in the batch were saved successfully — retry the ones listed here."- )- )---class ExternalDataJobSerializers(serializers.ModelSerializer):- schema = serializers.SerializerMethodField(read_only=True)- status = serializers.SerializerMethodField(read_only=True)- cdc_write_mode = serializers.SerializerMethodField(- read_only=True,- help_text=(- "For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob "- "rows produced per sync: `incremental_merge` (consolidated table) vs `scd2_append` "- "(cdc-only history table). `null` for non-CDC syncs. Read from `schema_snapshot`."- ),- )- billable = serializers.BooleanField(- read_only=True,- allow_null=True,- help_text=(- "Whether the rows synced by this job count toward billing. `false` for system-initiated "- "runs the customer isn't charged for (e.g. rebuilding a table after an internal issue). "- "`null` on legacy rows and means billable."- ),- )- destination_ids = serializers.ListField(- child=serializers.CharField(),- read_only=True,- help_text=(- "Destinations this run delivered to, snapshotted when it started. Empty on runs that "- "predate destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts "- "the rows read from the source once, not once per destination."- ),- )-- class Meta:- model = ExternalDataJob- fields = [- "id",- "created_at",- "created_by",- "finished_at",- "status",- "schema",- "rows_synced",- "latest_error",- "workflow_run_id",- "cdc_write_mode",- "billable",- "destination_ids",- ]- read_only_fields = [- "id",- "created_at",- "created_by",- "finished_at",- "status",- "schema",- "rows_synced",- "latest_error",- "workflow_run_id",- "cdc_write_mode",- "billable",- "destination_ids",- ]-- def get_cdc_write_mode(self, instance: ExternalDataJob) -> str | None:- return (instance.schema_snapshot or {}).get("cdc_write_mode")-- def get_status(self, instance: ExternalDataJob):- if instance.status == ExternalDataJob.Status.BILLING_LIMIT_REACHED:- return "Billing limits"-- if instance.status == ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW:- return "Billing limit too low"-- return instance.status-- def get_schema(self, instance: ExternalDataJob):- return SimpleExternalDataSchemaSerializer(- instance.schema, many=False, read_only=True, context=self.context- ).data---class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializers.ModelSerializer):- account_id = serializers.CharField(write_only=True)- client_secret = serializers.CharField(write_only=True)- last_run_at = serializers.SerializerMethodField(read_only=True)- created_by = serializers.SerializerMethodField(read_only=True)- latest_error = serializers.SerializerMethodField(read_only=True)- status = serializers.SerializerMethodField(read_only=True)- schemas = serializers.SerializerMethodField(read_only=True)- engine = serializers.ChoiceField(- source="connection_metadata.engine",- read_only=True,- allow_null=True,- required=False,- choices=DIRECT_CONNECTION_ENGINE_CHOICES,- help_text="Backend engine detected for the direct connection.",- )- revenue_analytics_config = ExternalDataSourceRevenueAnalyticsConfigSerializer(- source="revenue_analytics_config_safe", read_only=True- )- access_method = serializers.ChoiceField(choices=ExternalDataSource.AccessMethod.choices, read_only=True)- supports_webhooks = serializers.SerializerMethodField(read_only=True)- supports_column_selection = serializers.SerializerMethodField(- read_only=True,- help_text="Whether this source supports per-column sync selection via `enabled_columns`.",- )- # Optional on both create and update. On create, missing values default to `api`- # in the viewset to preserve backward compatibility with direct API callers that- # predate this field; the in-app UI and MCP tool always send it explicitly.- # `update` strips it to make the field write-once.- # `allow_null=True` because historical rows (created before migration 0049) have- # `created_via=NULL`, and the settings page spreads the GET payload back into PATCH.- created_via = serializers.ChoiceField(- choices=ExternalDataSource.CreatedVia.choices,- required=False,- allow_null=True,- help_text=(- "How this source was created. Defaults to `api` on create when omitted. "- "`web` for the in-app UI, `api` for direct API callers, `mcp` for agent/MCP tool calls, "- "`wizard` for the setup wizard and `self_driving` for the PostHog Desktop app "- "(both derived server-side from the caller's user agent). "- "Ignored on update."- ),- )- direct_query_enabled = serializers.BooleanField(- required=False,- help_text=(- "Whether this synced source is also live-queryable via direct connection. "- "Defaults to false for new sources; ignored for pure direct-query sources."- ),- )- auto_sync_new_schemas = serializers.BooleanField(- required=False,- help_text=(- "Automatically enable syncing for schemas discovered on this source after creation, "- "on both the scheduled discovery pass and manual schema refreshes. Defaults to false. "- "Not supported for direct-query sources."- ),- )- auto_sync_schema_patterns = serializers.ListField(- child=serializers.CharField(- max_length=250,- allow_blank=False,- help_text="An fnmatch-style glob pattern, e.g. `raw_*`.",- ),- required=False,- allow_null=True,- max_length=100,- help_text=(- "Optional fnmatch-style globs (`*` and `?` wildcards) restricting which newly discovered "- "schema names auto-sync, matched case-insensitively against both the qualified and bare "- "table name. Null or empty means every new schema qualifies. Only used when "- "`auto_sync_new_schemas` is true."- ),- )- api_version = serializers.CharField(- read_only=True,- allow_null=True,- help_text=(- "Vendor API version this source is pinned to (an opaque vendor label, e.g. a Stripe "- "date version). Null resolves to the source type's default version at sync time."- ),- )- api_version_deprecation = serializers.SerializerMethodField(- read_only=True,- help_text=(- "Set when the vendor has deprecated the API version this source is pinned to; "- "null otherwise. Drives the in-product deprecation warning."- ),- )-- class Meta:- model = ExternalDataSource- fields = [- "id",- "created_at",- "created_by",- "created_via",- "status",- "client_secret",- "account_id",- "source_type",- "latest_error",- "prefix",- "description",- "access_method",- "direct_query_enabled",- "auto_sync_new_schemas",- "auto_sync_schema_patterns",- "engine",- "last_run_at",- "schemas",- "job_inputs",- "revenue_analytics_config",- "user_access_level",- "supports_webhooks",- "supports_column_selection",- "api_version",- "api_version_deprecation",- ]- read_only_fields = [- "id",- "created_by",- "created_at",- "status",- "source_type",- "latest_error",- "last_run_at",- "schemas",- "engine",- "revenue_analytics_config",- "user_access_level",- "access_method",- "supports_webhooks",- "supports_column_selection",- "api_version",- "api_version_deprecation",- ]-- def to_representation(self, instance):- representation = super().to_representation(instance)-- job_inputs = representation.get("job_inputs", {})- if not isinstance(job_inputs, dict):- return representation-- # Derive allowed keys dynamically from source config field definitions- try:- source_type_model = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type_model)- split = get_nonsensitive_and_sensitive_field_names(source.get_source_config.fields)- # CDC fields aren't form fields but are non-secret operational config the UI needs.- nonsensitive = split.nonsensitive | _CDC_EXPOSED_JOB_INPUT_KEYS- except (ValueError, KeyError):- representation["job_inputs"] = {}- return representation-- # Normalize SSH tunnel legacy format before stripping- if "ssh_tunnel" in job_inputs and isinstance(job_inputs["ssh_tunnel"], dict):- tunnel = job_inputs["ssh_tunnel"]- # Normalize 'auth_type' (legacy from migration 0807) -> 'auth'- if "auth_type" in tunnel and "auth" not in tunnel:- tunnel["auth"] = tunnel.pop("auth_type")- if isinstance(tunnel.get("auth"), dict):- auth = tunnel["auth"]- # Normalize 'type' (legacy) -> 'selection'- if "type" in auth and "selection" not in auth:- auth["selection"] = auth.pop("type")- # Backfill require_tls default for sources created before the toggle existed- if "require_tls" not in tunnel:- tunnel["require_tls"] = {"enabled": True}-- stripped = strip_sensitive_from_dict(job_inputs, nonsensitive, split.sensitive)- declared = get_declared_field_names(source.get_source_config.fields)- representation["job_inputs"] = restore_declared_field_names(stripped, declared.hyphenated)- return representation-- def get_last_run_at(self, instance: ExternalDataSource) -> str | None:- latest_completed_run = instance.ordered_jobs[0] if instance.ordered_jobs else None # type: ignore-- return latest_completed_run.created_at.isoformat() if latest_completed_run else None-- def get_created_by(self, instance: ExternalDataSource) -> str | None:- return instance.created_by.email if instance.created_by else None-- def get_supports_webhooks(self, instance: ExternalDataSource) -> bool:- try:- source = SourceRegistry.get_source(ExternalDataSourceType(instance.source_type))- return isinstance(source, WebhookSource)- except Exception as e:- capture_exception(e)- return False-- def get_supports_column_selection(self, instance: ExternalDataSource) -> bool:- return source_supports_column_selection(instance.source_type)-- @extend_schema_field(ExternalDataSourceApiVersionDeprecationSerializer(allow_null=True))- def get_api_version_deprecation(self, instance: ExternalDataSource) -> dict[str, Any] | None:- return api_version_deprecation_payload(instance.source_type, instance.api_version)-- def _prefetched_schemas(self, instance: ExternalDataSource) -> list[ExternalDataSchema] | None:- prefetched = getattr(instance, "_prefetched_objects_cache", {}).get("schemas")- if prefetched is None:- return None- return [schema for schema in prefetched if not schema.deleted]-- def _active_schemas(self, instance: ExternalDataSource) -> list[ExternalDataSchema]:- """Schemas that are syncing or carry an error — derived in Python from the single `schemas`- prefetch rather than a second DB scan of the same (potentially huge) table."""- prefetched = self._prefetched_schemas(instance)- if prefetched is not None:- return [schema for schema in prefetched if schema.should_sync or schema.latest_error is not None]- return list(instance.schemas.exclude(deleted=True).filter(Q(should_sync=True) | Q(latest_error__isnull=False)))-- def get_status(self, instance: ExternalDataSource) -> str:- active_schemas: list[ExternalDataSchema] = self._active_schemas(instance)- # Negative statuses should ignore schemas the user has disabled — those can linger in- # active_schemas via the latest_error prefetch but shouldn't drag the source into a failed state.- syncing_schemas = [schema for schema in active_schemas if schema.should_sync]- any_failures = any(schema.status == ExternalDataSchema.Status.FAILED for schema in syncing_schemas)- any_billing_limits_reached = any(- schema.status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED for schema in syncing_schemas- )- any_billing_limits_too_low = any(- schema.status == ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW for schema in syncing_schemas- )- any_paused = any(schema.status == ExternalDataSchema.Status.PAUSED for schema in active_schemas)- any_running = any(schema.status == ExternalDataSchema.Status.RUNNING for schema in active_schemas)- any_completed = any(schema.status == ExternalDataSchema.Status.COMPLETED for schema in active_schemas)-- if any_failures:- return ExternalDataSchema.Status.FAILED- elif any_billing_limits_reached:- return "Billing limits"- elif any_billing_limits_too_low:- return "Billing limits too low"- elif any_paused:- return ExternalDataSchema.Status.PAUSED- elif any_running:- return ExternalDataSchema.Status.RUNNING- elif any_completed:- return ExternalDataSchema.Status.COMPLETED- else:- # Fallback during migration phase of going from source -> schema as the source of truth for syncs- return instance.status-- @extend_schema_field(serializers.CharField(allow_null=True))- def get_latest_error(self, instance: ExternalDataSource):- prefetched_schemas = self._prefetched_schemas(instance)- if prefetched_schemas is not None:- schema_with_error = next(- (schema for schema in prefetched_schemas if schema.latest_error is not None),- None,- )- else:- schema_with_error = instance.schemas.filter(latest_error__isnull=False).first()- return schema_with_error.latest_error if schema_with_error else None-- @extend_schema_field(serializers.ListField(child=serializers.DictField()))- def get_schemas(self, instance: ExternalDataSource):- prefetched_schemas = getattr(instance, "_prefetched_objects_cache", {}).get("schemas")- if prefetched_schemas is not None:- schemas = [schema for schema in prefetched_schemas if not schema.deleted]- else:- schemas = list(instance.schemas.exclude(deleted=True).order_by("name"))- # The source list embeds every schema of every source; large projects have tens of thousands.- # The list UI only reads a handful of per-schema fields, so serialize the trimmed shape there- # and reserve the full serializer for single-source reads.- if self.context.get("schemas_list_only"):- return ExternalDataSchemaListSerializer(schemas, many=True, read_only=True, context=self.context).data- return ExternalDataSchemaSerializer(schemas, many=True, read_only=True, context=self.context).data-- def update(self, instance: ExternalDataSource, validated_data: Any) -> Any:- request = self.context.get("request")- requested_access_method = request.data.get("access_method") if request is not None else None- if requested_access_method is not None and requested_access_method != instance.access_method:- raise ValidationError("Access method cannot be changed. Create a new source instead.")-- validated_data.pop("access_method", None)- # created_via is set at creation time and cannot be mutated afterwards- validated_data.pop("created_via", None)-- if validated_data.get("auto_sync_new_schemas") and instance.is_direct_query:- raise ValidationError(- "Auto-syncing new schemas is not supported for direct query sources, "- "because their schemas resolve at query time."- )-- incoming_prefix = validated_data.get("prefix", instance.prefix)-- if instance.is_direct_query:- # For direct query sources the prefix acts as the user-facing source name.- normalized_prefix = incoming_prefix.strip() if isinstance(incoming_prefix, str) else ""- if not normalized_prefix:- raise ValidationError("Name is required for direct query sources")- if ExternalDataSource.is_system_managed_prefix(normalized_prefix):- raise ValidationError(RESERVED_SOURCE_NAME_MESSAGE)- validated_data["prefix"] = normalized_prefix- else:- validated_data["prefix"] = instance.prefix-- existing_job_inputs = instance.job_inputs or {}- job_inputs_were_submitted = "job_inputs" in validated_data- incoming_job_inputs = validated_data.get("job_inputs", {})-- source_type_model = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type_model)- sensitive_fields = get_sensitive_field_names(source.get_source_config.fields)- declared_field_names = get_declared_field_names(source.get_source_config.fields)- discovered_schemas: list[SourceSchema] | None = None-- new_job_inputs = {**existing_job_inputs, **incoming_job_inputs}-- # CDC resource ownership changes must go through the CDC-specific endpoints.- for key in _CDC_EXPOSED_JOB_INPUT_KEYS:- if key in existing_job_inputs:- new_job_inputs[key] = existing_job_inputs[key]- else:- new_job_inputs.pop(key, None)-- # Server-managed job_inputs (Custom's OAuth2 row pointer, GitHub's legacy `repository`- # marker): pin each to the stored value so an editor can't repoint the source at a different- # row/marker (and through it, different credentials). Re-entered auth_oauth2_* secrets flow- # into the pinned row during credential validation. The source declares which fields these- # are — the API never names the source type.- for field in source.server_managed_job_input_fields(incoming_job_inputs, existing_job_inputs):- if existing_job_inputs.get(field):- new_job_inputs[field] = existing_job_inputs[field]- else:- new_job_inputs.pop(field, None)-- # If the connection target changed, require credentials to be re-entered. Covers- # both the generic `host` field and source-specific URL fields like ServiceNow's- # `instance_url`, so a stored credential can't be redirected to a new host.- connection_host_changed = any(- field in incoming_job_inputs- and connection_target_changed(existing_job_inputs.get(field), incoming_job_inputs[field])- for field in _CONNECTION_TARGET_FIELDS- )-- # Some sources keep their connection target in a differently named field (e.g. Okta's- # `okta_domain`, Freshdesk's `subdomain`). Changing one would send the preserved credential- # to a new host — the same exfiltration risk as a `host` change — so require re-entry too.- connection_host_changed = connection_host_changed or any(- field in incoming_job_inputs- and connection_target_changed(existing_job_inputs.get(field), incoming_job_inputs[field])- for field in source.connection_host_fields- )-- # If the SSH tunnel's connection target changed, also require credentials. Without this an- # editor could swap in a tunnel that routes the backend's auth to an attacker-controlled- # server, exfiltrating the stored database credentials (VERIA-311).- ssh_tunnel_changed = "ssh_tunnel" in incoming_job_inputs and ssh_tunnel_connection_changed(- existing_job_inputs.get("ssh_tunnel"),- incoming_job_inputs.get("ssh_tunnel"),- )-- # Some sources keep their connection target somewhere other than a named field — Custom's- # lives inside its manifest. An edit that introduces a new request host would send the- # preserved credential somewhere it wasn't going before, the same exfiltration risk, so- # require re-entry too. The source decides; the API never names the source type.- job_inputs_host_added = source.job_inputs_add_connection_host(incoming_job_inputs, existing_job_inputs)-- # Some sources keep their secrets in a bound row, not job_inputs (Custom's- # CustomOAuth2Integration) — the generic preserved-credentials check can't see those, yet a- # host change would still redirect the row's injected token. The source reports whether such- # row-backed secrets are preserved (not re-entered) on this update.- preserved_row_backed_credentials = source.has_preserved_row_backed_credentials(instance, incoming_job_inputs)-- if connection_host_changed or ssh_tunnel_changed or job_inputs_host_added:- gate_sensitive_fields = sensitive_fields - _CREATION_ONLY_SECRET_FIELDS- preserved_credentials = has_preserved_credentials(- existing_job_inputs,- incoming_job_inputs,- gate_sensitive_fields,- nested_containers=(*_NESTED_AUTH_CONTAINERS, *declared_field_names.switch_groups),- )- if preserved_credentials or preserved_row_backed_credentials:- if ssh_tunnel_changed:- raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")- if job_inputs_host_added:- raise ValidationError("Changing the manifest's request host requires re-entering your credentials.")- raise ValidationError("Changing the connection host requires re-entering your credentials.")-- # Preserve sensitive credentials not explicitly provided (API response omits them for security)- for key in sensitive_fields:- if existing_job_inputs.get(key) and not incoming_job_inputs.get(key):- new_job_inputs[key] = existing_job_inputs[key]-- # SSH tunnel is a nested config - deep-merge it so partial updates preserve existing fields- existing_ssh_tunnel = existing_job_inputs.get("ssh_tunnel")-- # Nested containers (e.g. Stripe `auth_method`, Snowflake `auth_type`, Billomat `registered_app`)- # need a deep-merge that preserves sensitive fields not explicitly provided. The shallow merge- # above would otherwise wipe redacted credentials nested inside these containers. Same container- # list as the host-change gate above, so a merge here always has a matching preserved-credential check.- for container_key in _NESTED_AUTH_CONTAINERS:- existing_container = existing_job_inputs.get(container_key)- incoming_container = incoming_job_inputs.get(container_key)- if incoming_container is not None and not isinstance(incoming_container, dict):- raise ValidationError({"job_inputs": {container_key: "Must be an object."}})- if not (isinstance(existing_container, dict) and isinstance(incoming_container, dict)):- continue- selection_changed = existing_container.get("selection") != incoming_container.get("selection")- if selection_changed:- # Selection switched (e.g. password→keypair) — use only incoming, don't carry over old secrets- new_job_inputs[container_key] = incoming_container- else:- merged_container = {**existing_container, **incoming_container}- for key in sensitive_fields:- if existing_container.get(key) and not incoming_container.get(key):- merged_container[key] = existing_container[key]- new_job_inputs[container_key] = merged_container-- # Switch groups are nested containers too. The settings form submits only the fields the- # user touched and skips a disabled group's children, so a payload that just flips- # `enabled` would otherwise replace the whole stored group and drop a required nested- # value that validation then rejects. Switching a group off keeps its stored value —- # the user hasn't asked to forget it, and consumers gate on `enabled` before reading it.- for group_key in declared_field_names.switch_groups:- # A group declared with a hyphen can be stored under either spelling (see- # `restore_declared_field_names`), so resolve both sides by declared name.- incoming_key = _stored_key(incoming_job_inputs, group_key)- if incoming_key is None:- continue- incoming_group = incoming_job_inputs[incoming_key]- if not isinstance(incoming_group, dict):- raise ValidationError({"job_inputs": {group_key: "Must be an object."}})- existing_group = _stored_value(existing_job_inputs, group_key)- if not isinstance(existing_group, dict):- continue- merged_group = {**existing_group, **incoming_group}- # No switch group declares a secret today, but keep the carry-over so one could.- for key in sensitive_fields:- if existing_group.get(key) and not incoming_group.get(key):- merged_group[key] = existing_group[key]- # Drop the other spelling so parsing can't see two competing groups.- for key in _name_variants(group_key):- new_job_inputs.pop(key, None)- new_job_inputs[incoming_key] = merged_group-- incoming_ssh_tunnel = incoming_job_inputs.get("ssh_tunnel")- if existing_ssh_tunnel and incoming_ssh_tunnel is not None:- ssh_tunnel_host_changed = "host" in incoming_ssh_tunnel and incoming_ssh_tunnel[- "host"- ] != existing_ssh_tunnel.get("host")-- # Deep-merge: start with existing, overlay incoming top-level keys- merged_ssh_tunnel = {**existing_ssh_tunnel, **incoming_ssh_tunnel}-- # Check both 'auth' (new format) and 'auth_type' (legacy format from migration 0807)- existing_auth = (- (existing_ssh_tunnel or {}).get("auth") or (existing_ssh_tunnel or {}).get("auth_type") or {}- )- incoming_auth = (- (incoming_ssh_tunnel or {}).get("auth") or (incoming_ssh_tunnel or {}).get("auth_type") or {}- )-- if ssh_tunnel_host_changed and not incoming_auth:- raise ValidationError("Changing the SSH tunnel host requires re-entering your SSH credentials.")-- if not incoming_auth:- # No auth in incoming request - preserve entire existing auth- merged_ssh_tunnel["auth"] = {**existing_auth}- else:- # Merge auth, preserving sensitive fields not explicitly provided- merged_auth = {**incoming_auth}- if not ssh_tunnel_host_changed:- for key in ("password", "passphrase", "private_key"):- if existing_auth.get(key) and not incoming_auth.get(key):- merged_auth[key] = existing_auth[key]- merged_ssh_tunnel["auth"] = merged_auth-- new_job_inputs["ssh_tunnel"] = merged_ssh_tunnel-- is_valid, errors = source.validate_config(new_job_inputs)- if not is_valid:- raise ValidationError(f"Invalid source config: {', '.join(errors)}")-- # Clearing a multi-schema source's namespace migrates legacy rows to qualified naming.- old_schema = detect_sql_schema_clear_transition(- source_type=instance.source_type,- existing_job_inputs=existing_job_inputs,- incoming_job_inputs=incoming_job_inputs,- )- if old_schema is not None:- apply_sql_warehouse_schema_clear_migration(instance, old_schema)-- source_config: Config = source.parse_config(new_job_inputs)- validated_job_inputs = source_config.to_dict()-- # The settings form resubmits the whole connection config on every save, so changing an- # unrelated setting (auto-syncing new tables, the prefix, the description) re-probed the- # live connection too — and a momentarily unreachable database then failed the whole save,- # leaving nothing to do but retry. Compare the parsed config against what's stored so the- # probe below only runs when the connection actually changed. Direct query sources still- # probe on every save: the same call refreshes their schemas and connection metadata.- try:- stored_job_inputs = source.parse_config(existing_job_inputs).to_dict()- except Exception:- # A stored config that no longer parses can't be compared, so treat it as changed and- # let the probe run rather than skipping validation on a config we can't read.- stored_job_inputs = None- connection_config_changed = stored_job_inputs is None or stored_job_inputs != validated_job_inputs-- for key in _CDC_EXPOSED_JOB_INPUT_KEYS:- if key in existing_job_inputs:- validated_job_inputs[key] = existing_job_inputs[key]- validated_data["job_inputs"] = validated_job_inputs-- if job_inputs_were_submitted and (connection_config_changed or instance.is_direct_query):- effective_api_version = source.resolve_api_version(instance.api_version)- try:- if isinstance(source, (PostgresSource, MySQLSource)):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config),- instance.team_id,- instance.access_method,- api_version=effective_api_version,- )- elif isinstance(source, CustomSource):- # Pass the source being updated so an integration-backed OAuth2 source can only validate- # with the integration bound to it — not another source's, whose token the probe would- # otherwise mint and send to the submitted manifest host. owner_user_id additionally gates- # an as-yet-unbound integration to its creator.- credentials_valid, credentials_error = source.validate_credentials(- source_config,- instance.team_id,- source_id=str(instance.pk),- owner_user_id=self.context["request"].user.id,- api_version=effective_api_version,- )- else:- credentials_valid, credentials_error = source.validate_credentials(- source_config, instance.team_id, api_version=effective_api_version- )- except Exception as e:- credentials_valid, credentials_error = _credentials_validation_failed(source, instance.team_id, e)- if not credentials_valid:- raise ValidationError(credentials_error or INVALID_CREDENTIALS_FALLBACK_MESSAGE)- if instance.is_direct_query:- discovered_schemas = source.get_schemas(- source_config, instance.team_id, api_version=effective_api_version- )- validated_data["connection_metadata"] = get_direct_connection_metadata(- source_impl=source,- source_config=source_config,- team_id=instance.team_id,- source_model=instance,- fallback=instance.connection_metadata,- )-- if job_inputs_were_submitted and isinstance(source, CustomSource):- # Credential validation adopts re-entered OAuth2 secrets into the integration row and- # rewrites the config (pointer set, static secrets cleared) — re-serialize so job_inputs- # stores the pointer and never the raw secrets.- validated_job_inputs = source_config.to_dict()- for key in _CDC_EXPOSED_JOB_INPUT_KEYS:- if key in existing_job_inputs:- validated_job_inputs[key] = existing_job_inputs[key]- validated_data["job_inputs"] = validated_job_inputs-- # Namespaced-resource sources (GitHub repos) track their schema rows against a resource- # set in job_inputs; capture the old set before the write so we can reconcile after.- namespaced_adapter = get_namespaced_resource_adapter(source_type_model)- old_namespaced_resources: list[str] = []- if namespaced_adapter is not None and job_inputs_were_submitted:- old_namespaced_resources = namespaced_adapter.resources_for_job_inputs(existing_job_inputs)-- updated_source: ExternalDataSource = super().update(instance, validated_data)-- if namespaced_adapter is not None and job_inputs_were_submitted:- # Adds schema rows for added resources, retires removed ones, and reconciles their- # webhooks. No-op when the effective resource list didn't change.- namespaced_adapter.reconcile_resources(- source_model=updated_source,- team=instance.team,- old_resources=old_namespaced_resources,- new_config=source_config,- )-- if updated_source.is_direct_query and discovered_schemas is not None:- schema_names = {schema.name: schema.label for schema in discovered_schemas}- descriptions = {schema.name: schema.description for schema in discovered_schemas}-- with transaction.atomic():- ExternalDataSource._base_manager.filter(pk=updated_source.pk).select_for_update().get()- engine = get_direct_query_engine(updated_source.direct_engine)- name_substitutions = _refresh_name_substitutions(- engine, source=updated_source, source_schemas=discovered_schemas, team_id=instance.team_id- )- if name_substitutions:- schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}- descriptions = {- name_substitutions.get(name, name): description for name, description in descriptions.items()- }- sync_old_schemas_with_new_schemas(- schema_names,- source_id=str(updated_source.id),- team_id=instance.team_id,- descriptions=descriptions,- )- # Direct call on the engine adapter (not the source hook) so tests mocking- # `SourceRegistry.get_source` still exercise the real DataWarehouseTable rebuild.- if engine is not None:- engine.reconcile_schemas(- source=updated_source, source_schemas=discovered_schemas, team_id=instance.team_id- )-- schemas = list(- ExternalDataSchema.objects.filter(team_id=instance.team_id, source_id=updated_source.id)- .exclude(deleted=True)- # This is the update() response path, which serializes the full column shape- # (include_columns=True) — building columns reads table.credential.access_key per schema,- # so keep the credential joined here to avoid an N+1.- .select_related("table__credential", "table__external_data_source")- .order_by("name")- )- # `get_status`/`get_latest_error` derive the active/errored subset from this prefetch, so no- # separate `active_schemas` query is needed.- updated_source_any = cast(Any, updated_source)- updated_source_any._prefetched_objects_cache = {"schemas": schemas}-- return updated_source---class ExternalDataSourceCreateSerializer(serializers.Serializer):- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- help_text="The source type (e.g. 'Postgres', 'Stripe').",- )- payload = serializers.DictField(- help_text=(- "Connection credentials. Keys depend on source_type. Add a 'schemas' array to pick "- "which tables sync; omit it and every discovered table syncs with default settings."- ),- )- prefix = serializers.CharField(- max_length=100,- required=False,- allow_null=True,- allow_blank=True,- help_text="Prefix added to the table names PostHog creates in HogQL. Does not filter which tables are imported.",- )- description = serializers.CharField(- max_length=400, required=False, allow_null=True, allow_blank=True, help_text="Human-readable description."- )- access_method = serializers.ChoiceField(- choices=ExternalDataSource.AccessMethod.choices,- required=False,- default=ExternalDataSource.AccessMethod.WAREHOUSE,- help_text="Connection mode: 'warehouse' (import) or 'direct' (live query).",- )- created_via = serializers.ChoiceField(- # `wizard` and `self_driving` are intentionally omitted: they are never accepted from a- # caller (that would let any client self-label as wizard- or self-driving-created). They- # are derived server-side by upgrading a machine-injected `mcp` value based on the request- # transport (the wizard, PostHog Desktop, or the wizard's self-driving program).- choices=[- ExternalDataSource.CreatedVia.WEB,- ExternalDataSource.CreatedVia.API,- ExternalDataSource.CreatedVia.MCP,- ],- required=False,- default=ExternalDataSource.CreatedVia.API,- help_text=(- "Where the request came from: `web` for the in-app UI, `api` for direct API callers, "- "`mcp` for agent/MCP tool calls. `wizard` and `self_driving` cannot be set directly — "- "they are derived server-side for wizard- and PostHog Desktop-driven MCP calls. Defaults to `api`."- ),- )- direct_query_enabled = serializers.BooleanField(- required=False,- default=False,- help_text=(- "Whether a synced source should also be live-queryable via direct connection. "- "Defaults to false; ignored for pure direct-query sources."- ),- )- destination_ids = serializers.ListField(- child=serializers.UUIDField(),- required=False,- help_text=(- "Destinations every table on this source writes to. Set here rather than afterwards, "- "so the opening sync already carries them. Omit to write to the PostHog warehouse only."- ),- )---class SourceSetupSerializer(serializers.Serializer):- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- help_text="The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').",- )- payload = serializers.DictField(- required=False,- help_text=(- "Connection details as flat keys for the source_type (discover required fields with the wizard "- "tool). Prefer references over raw secrets: pass {'credential_id': <id>} referencing the connection "- "details the user stored via the connect-link page (discover ids with the stored_credentials "- "endpoint) — they are merged in server-side and deleted once consumed. An already-connected OAuth "- "integration can be passed via its id key instead (e.g. {'hubspot_integration_id': 123}). "- "For source_type 'Custom' (a user-defined REST API) the keys are 'manifest_json' (a stringified "- "RESTAPIConfig describing client.base_url, auth, and resources) plus the credential for the auth "- "type the manifest declares — 'auth_token' (bearer), 'auth_api_key' (api_key), or 'auth_password' "- "(http_basic); keep secrets in these auth_* keys, never inline in the manifest. "- "A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible "- "sync defaults."- ),- )- prefix = serializers.CharField(- max_length=100,- required=False,- allow_null=True,- allow_blank=True,- help_text=(- "Prefix added to the table names PostHog creates in HogQL, e.g. 'stripe' produces stripe_charges. "- "Does not filter which tables are imported. Defaults to the source type."- ),- )- description = serializers.CharField(- max_length=400, required=False, allow_null=True, allow_blank=True, help_text="Human-readable description."- )- direct_query_enabled = serializers.BooleanField(- required=False,- default=False,- help_text=(- "Whether a synced source should also be live-queryable via direct connection. "- "Defaults to false; ignored for pure direct-query sources."- ),- )---class SourceSetupWebhookSerializer(serializers.Serializer):- success = serializers.BooleanField(- help_text=(- "Whether the webhook was registered with the external service. When true, webhook-capable tables "- "(including webhook-only ones) sync via real-time webhooks; when false, tables fall back to the "- "polling sync defaults and webhook-only tables stay disabled."- )- )- webhook_url = serializers.CharField(- allow_null=True, help_text="The PostHog endpoint the external service delivers events to."- )- error = serializers.CharField(- allow_null=True, help_text="Why webhook registration failed (e.g. the credentials lack webhook permissions)."- )- pending_inputs = serializers.ListField(- child=serializers.CharField(),- help_text=(- "Webhook input names the user still needs to provide (e.g. a signing secret the external API did not "- "return on create). Submit them via the update_webhook_inputs endpoint."- ),- )---class SourceSetupResponseSerializer(serializers.Serializer):- id = serializers.UUIDField(help_text="ID of the created external data source.")- webhook = SourceSetupWebhookSerializer(- required=False,- help_text=(- "Outcome of automatic webhook registration. Only present for sources that support webhooks "- "(e.g. Stripe) and have webhook-capable tables."- ),- )---class ExternalDataSourceCreateResponseSerializer(serializers.Serializer):- id = serializers.UUIDField(help_text="ID of the created external data source.")---class ExternalDataSourceErrorResponseSerializer(serializers.Serializer):- message = serializers.CharField(help_text="Human-readable explanation of why the source could not be created.")---class SourceConnectLinkSerializer(serializers.Serializer):- source_type = serializers.CharField(help_text="The source type the link is for.")- auth_method = serializers.ChoiceField(- choices=["oauth", "credentials"],- help_text=(- "What the user will do on the connect page: 'oauth' = authorize an account in their browser; "- "'credentials' = enter connection details (or pick OAuth where the source offers both). Either "- "way secrets never pass through the agent, and the result is always a stored credential id."- ),- )- connect_url = serializers.CharField(- help_text=(- "Full URL to share with the user. It opens the source's connection form in PostHog — "- "credentials never pass through the agent or the chat."- )- )- instructions = serializers.CharField(help_text="Next steps for the agent to relay to the user.")---class SourceCredentialCreateSerializer(serializers.Serializer):- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- help_text="The source type these credentials are for (e.g. 'Stripe', 'Postgres').",- )- payload = serializers.DictField(- help_text=(- "Connection details as flat keys for the source_type — the same fields the create flow accepts "- "(host, port, password, API key, …). Checked against a live connection before being stored."- ),- )---class SourceCredentialSerializer(serializers.Serializer):- credential_id = serializers.UUIDField(- help_text="Stored credential id. Pass to the setup endpoint as {'credential_id': <id>} to create the source."- )- source_type = serializers.CharField(help_text="The source type the stored credentials are for.")- created_at = serializers.DateTimeField(help_text="When the credentials were stored.")- expires_at = serializers.DateTimeField(- help_text="When the stored credentials expire. Unconsumed credentials are unusable past this time."- )---def _find_unresolved_secret_refs(payload: Any) -> list[str]:- """Return payload keys whose value is an unresolved secret reference.-- The wizard CLI's `wizard_ask` returns sensitive answers as `{"secretRef": "..."}` objects that the- caller must resolve to real values before they reach PostHog. If one slips through, source creation- fails downstream with a confusing "invalid credentials"/"invalid API key" error — detect it up front- so the agent gets an actionable message instead.- """- if not isinstance(payload, dict):- return []- return [key for key, value in payload.items() if isinstance(value, dict) and "secretRef" in value]---def _unresolved_secret_ref_response(payload: Any) -> Response | None:- offenders = _find_unresolved_secret_refs(payload)- if not offenders:- return None- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": (- f"Unresolved secret reference(s) for: {', '.join(sorted(offenders))}. These fields are still "- "`{'secretRef': ...}` objects — PostHog cannot resolve them. Resolve the secret to its real "- "value before calling (or collect credentials via data-warehouse-source-connect-link and pass "- "the resulting credential_id instead)."- )- },- )---def _find_top_level_oauth_field(config: dict) -> dict | None:- """Find a top-level OAuth field ({type: 'oauth', kind, name, ...}) in a source config dump.-- Only a top-level OAuth field makes a source OAuth-only (e.g. Hubspot). An OAuth option- nested inside a select (e.g. Stripe's auth_method) coexists with credential options, so- those sources route to the credentials connect page — its form still offers the OAuth- choice alongside API keys.- """- for field in config.get("fields") or []:- if isinstance(field, dict) and field.get("type") == "oauth" and field.get("kind"):- return field- return None---class DatabaseSchemaRequestSerializer(serializers.Serializer):- """Validate credentials and preview available tables from a remote database.-- The request body contains source_type plus flat source-specific credential fields- (e.g. host, port, database, user, password, schema for Postgres). The credential- fields vary per source_type and are validated dynamically by the source registry.-- For source_type "Custom" (a user-defined REST API) the body carries `manifest_json`- (a stringified RESTAPIConfig describing client.base_url, auth, and resources) plus the- credential for the manifest's declared auth type — `auth_token` (bearer), `auth_api_key`- (api_key), or `auth_password` (http_basic); keep secrets in these auth_* keys, never- inline in manifest_json. The returned tables mirror the manifest's resources, with- detected primary keys and incremental cursors.- """-- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- help_text="The source type to validate against.",- )---class SourcePreviewRequestSerializer(serializers.Serializer):- source_type = serializers.ChoiceField(- choices=ExternalDataSourceType.choices,- help_text="The source type to preview. Only 'Custom' (a user-defined REST API) is supported today.",- )- payload = serializers.DictField(- required=False,- help_text=(- "Source config as flat keys. For source_type 'Custom': 'manifest_json' (a stringified RESTAPIConfig "- "describing client.base_url, auth, and resources) plus the credential for the manifest's declared auth "- "type — 'auth_token' (bearer), 'auth_api_key' (api_key), or 'auth_password' (http_basic). Secrets stay "- "in these auth_* keys, never inline in the manifest."- ),- )- resource_name = serializers.CharField(- help_text="Which manifest resource (table) to read a sample from — one of the resource names in manifest_json.",- )- limit = serializers.IntegerField(- required=False,- default=PREVIEW_DEFAULT_ROWS,- min_value=1,- max_value=PREVIEW_MAX_ROWS,- help_text=f"Maximum sample rows to return (1–{PREVIEW_MAX_ROWS}). Defaults to {PREVIEW_DEFAULT_ROWS}.",- )---class SourcePreviewColumnSerializer(serializers.Serializer):- name = serializers.CharField(help_text="Column name as it appears in the previewed rows.")- type = serializers.CharField(- help_text="JSON type inferred from the first non-null value: string, integer, number, boolean, object, array, or null."- )---class SourcePreviewResponseSerializer(serializers.Serializer):- rows = serializers.ListField(- child=serializers.DictField(),- help_text="Up to `limit` sample rows, after data_selector extraction — the raw records the sync would ingest.",- )- row_count = serializers.IntegerField(help_text="Number of sample rows returned (≤ limit).")- columns = SourcePreviewColumnSerializer(- many=True,- help_text="Columns observed across the sample rows, each with an inferred JSON type.",- )- error = serializers.CharField(- allow_null=True,- help_text=(- "Set when the live read failed (e.g. the host was unreachable or returned an auth error); rows is then "- "empty. Manifest, validation, and SSRF problems return HTTP 400 instead of populating this field."- ),- )---class DraftCustomManifestRequestSerializer(serializers.Serializer):- source_name = serializers.CharField(- required=False,- allow_blank=True,- default="",- help_text="Optional human name of the API being connected (e.g. 'Acme CRM'). Used only to orient the model.",- )- docs_url = serializers.URLField(- required=False,- allow_blank=True,- help_text="URL of the API documentation to read. Provide this or docs_text; fetched server-side via the egress proxy.",- )- docs_text = serializers.CharField(- required=False,- allow_blank=True,- help_text="Raw API documentation or an OpenAPI/Swagger spec, pasted directly. Provide this or docs_url.",- )-- def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:- # Strip first: a whitespace-only docs_text is truthy but useless (it'd fetch an empty URL).- if not ((attrs.get("docs_url") or "").strip() or (attrs.get("docs_text") or "").strip()):- raise serializers.ValidationError("Provide either docs_url or docs_text.")- return attrs---class DraftCustomManifestResponseSerializer(serializers.Serializer):- draft_status = serializers.ChoiceField(- choices=["ok", "invalid", "model_error"],- help_text=(- "'ok' = a manifest validated; 'invalid' = a manifest was drafted but never validated within the budget "- "(see error; manifest_json holds the last attempt to fix by hand); 'model_error' = the model returned no "- "usable JSON."- ),- )- manifest_json = serializers.CharField(- allow_null=True,- help_text="The drafted RESTAPIConfig manifest as a JSON string (non-secret), or null if none was produced.",- )- resource_names = serializers.ListField(- child=serializers.CharField(),- help_text="Names of the resources (tables) the validated manifest exposes. Empty unless draft_status is 'ok'.",- )- attempts = serializers.IntegerField(- help_text="How many draft→validate→repair rounds were run.",- )- error = serializers.CharField(- allow_null=True,- help_text="The last validation error when draft_status is not 'ok'; null on success.",- )---class SimpleExternalDataSourceSerializers(serializers.ModelSerializer):- class Meta:- model = ExternalDataSource- fields = [- "id",- "created_at",- "created_by",- "status",- "source_type",- ]- read_only_fields = ["id", "created_by", "created_at", "status", "source_type"]---class IntegrationAccountSerializer(serializers.Serializer):- """A selectable account/resource exposed by an OAuth integration, in the shared shape every ad- platform produces (see ``IntegrationAccount`` in the data-imports common module). One serializer- and one frontend selector work across all platforms."""-- value = serializers.CharField(- help_text="The identifier stored in the source config and used for API calls (numeric account id as a string, a site url, etc.)."- )- display_name = serializers.CharField(help_text="Primary human-readable label for the account.")- is_primary = serializers.BooleanField(- help_text="True when this account belongs to the connected user's own (primary) account context, rather than one they merely have access to. Sorted/marked first."- )- badges = serializers.ListField(- child=serializers.CharField(),- help_text="Short status chips for the account, e.g. ['Active'] or ['Pause'].",- )- group = serializers.CharField(- allow_null=True,- help_text="Optional grouping label for hierarchical platforms (e.g. the owning customer/manager name).",- )- secondary_text = serializers.CharField(- allow_null=True,- help_text="Extra identifier shown in parentheses and searchable, e.g. the alphanumeric account number.",- )---class IntegrationAccountsResponseSerializer(serializers.Serializer):- accounts = IntegrationAccountSerializer(- many=True,- help_text="All accounts the connected integration can access.",- )---class AccountPickerManagementPermission(TeamMemberAdminManagementPermission):- """Admin gate for the account picker, with a message the customer can act on.-- The base message names no next step. Free entry stays open on the account field, so a- member who cannot list accounts can still finish the source by filling the account in.- """-- message = (- "You need admin access to this project to list the accounts this connection can reach. "- "Ask an admin to finish the setup, or fill in the account yourself."- )--[email protected](frozen=True, kw_only=True, slots=True)-class ResolvedStoredCredential:- payload: dict = dataclasses.field(repr=False)- credential: PendingSourceCredential | None- error_response: Response | None---@extend_schema(extensions={"x-product": "warehouse_sources"})-class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):- """- Create, Read, Update and Delete External data Sources.- """-- scope_object = "external_data_source"- scope_object_write_actions = [- "create",- "update",- "partial_update",- "patch",- "destroy",- "reload",- "refresh_schemas",- "bulk_update_schemas",- "database_schema",- "setup",- "store_credentials",- "source_prefix",- "revenue_analytics_config",- "destinations",- "create_webhook",- "update_webhook_inputs",- "delete_webhook",- "check_cdc_prerequisites",- "check_cdc_prerequisites_for_source",- "enable_cdc",- "disable_cdc",- "repair_cdc",- "update_cdc_settings",- # Enumerates the connected provider's accounts/sites — write-scoped so a read-only token can't- # list them (info disclosure); also gated behind admin in dangerously_get_permissions.- "oauth_accounts",- # Live outbound HTTP to a caller-supplied manifest (including POSTs) — a- # side-effecting action, so it needs write scope, not read.- "preview_resource",- # Fetches a caller-supplied docs URL and calls the (paid) LLM gateway — side-effecting.- "draft_custom_manifest",- ]- scope_object_read_actions = [- "list",- "retrieve",- "jobs",- "wizard",- "connect_link",- "stored_credentials",- "webhook_info",- "cdc_status",- ]- queryset = ExternalDataSource.objects.all()- serializer_class = ExternalDataSourceSerializers- filter_backends = [filters.SearchFilter]- # `source_id` is an opaque internal connection UUID — useless to search by. Callers- # (the in-app sources list, the MCP tool) narrow by what they can actually see: the- # source type ("Stripe", "Postgres") and the HogQL table prefix.- search_fields = ["source_type", "prefix"]- ordering = "-created_at"-- def check_object_permissions(self, request: Request, obj: Any) -> None:- super().check_object_permissions(request, obj)- if request.method not in ("GET", "HEAD", "OPTIONS") and isinstance(obj, ExternalDataSource):- if obj.is_system_managed:- raise PermissionDenied("This source is managed by PostHog and cannot be changed through this API.")-- def _assert_can_write_schemas(self, schemas: Iterable[ExternalDataSchema]) -> None:- """Per-table gate for source-level endpoints that write or sync schemas.-- Editor on the source isn't enough: a table can be locked below that, and these endpoints- never resolve a schema through DRF's object permissions, so nothing else checks it. Each- schema resolves like the schema viewset's permission: through its table, which falls back- to the source via RESOURCE_FALLBACK_MAP.- """- # Service credentials are synthetic users UserAccessControl can't evaluate; they're gated by- # API scope + project membership. Mirror AccessControlPermission.- if is_service_auth(self.request):- return- uac = self.user_access_control- for schema in schemas:- level = uac.get_user_access_level(schema.table or schema.source)- if level is None or not access_level_satisfied_for_resource("warehouse_table", level, "editor"):- raise PermissionDenied("You do not have editor access to every table in this source.")-- def dangerously_get_permissions(self):- if self.action == "connections":- return [- IsAuthenticated(),- APIScopePermission(),- TeamMemberAccessPermission(),- ]- # The account picker enumerates every account/site the connected provider exposes, so require- # manage access even though it's a GET — a read-only member shouldn't discover unrelated- # accounts (info disclosure). Other actions fall back to the viewset defaults.- if self.action == "oauth_accounts":- return [- IsAuthenticated(),- APIScopePermission(),- AccessControlPermission(),- TeamMemberAccessPermission(),- AccountPickerManagementPermission(),- ]- raise NotImplementedError()-- def get_throttles(self):- # The AI manifest builder fans out to several Opus calls per request and isn't billed to the- # customer, so cap it per team: a burst guard against double-submits/retries, an hourly window- # for an intense setup session, and a daily backstop against scripted abuse.- if self.action == "draft_custom_manifest":- return [- CustomSourceAIBuilderBurstThrottle(),- CustomSourceAIBuilderSustainedThrottle(),- CustomSourceAIBuilderDailyThrottle(),- ]- return super().get_throttles()-- def finalize_response(self, request: Request, response: Response, *args: Any, **kwargs: Any) -> Response:- response = super().finalize_response(request, response, *args, **kwargs)- # Tag the request span with the two things that drive source-list load cost — source count and- # total serialized schema count — so the historically-slow list endpoint is diagnosable in- # tracing. Done here rather than by overriding `list`, since a method named `list` would shadow- # the builtin `list[...]` type used in annotations elsewhere in this class. Guarded for shape- # because finalize_response also runs for error responses (no `results`) and other actions.- if self.action == "list" and isinstance(response.data, dict):- results = response.data.get("results")- if isinstance(results, list):- span = trace.get_current_span()- span.set_attribute("data_warehouse.sources.count", len(results))- span.set_attribute(- "data_warehouse.sources.schemas.count",- sum(len(source.get("schemas") or []) for source in results if isinstance(source, dict)),- )- return response-- def get_serializer_class(self) -> type[serializers.Serializer]:- if self.action == "create":- return ExternalDataSourceCreateSerializer- if self.action == "database_schema":- return DatabaseSchemaRequestSerializer- return ExternalDataSourceSerializers-- def get_serializer_context(self) -> dict[str, Any]:- context = super().get_serializer_context()- # Building the full HogQL Database and serializing per-schema table columns is expensive- # and only needed when a caller reads `schemas[].table.columns` — which the source list view- # never does (it only reads name/row_count). Gate both to single-source reads.- include_columns = self.action != "list"- context["include_columns"] = include_columns- # The list serializes a trimmed per-schema shape; single-source reads serialize the full one.- context["schemas_list_only"] = self.action == "list"- if include_columns:- context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))-- return context-- def safely_get_queryset(self, queryset):- queryset = queryset.exclude(deleted=True)- canonical_source = _canonical_legacy_managed_warehouse_source(queryset.filter(team_id=self.team_id))- queryset = _hide_noncanonical_managed_warehouse_sources(queryset, canonical_source)-- # `table__credential` holds EncryptedTextField key material. The list never reads it (trimmed- # schema shape, include_columns=False), so joining it across every schema — tens of thousands on- # large sources — is pure waste there and is dropped. Every other action serializes columns- # (include_columns=True), and building them reads `table.credential.access_key` per schema- # (see DataWarehouseTable.hogql_definition), so keep the join off the list path only.- schema_select = ["table__external_data_source"]- if self.action != "list":- schema_select.append("table__credential")-- return (- queryset- # created_by (FK) and revenue_analytics_config (reverse 1:1) are read per source during- # serialization. select_related folds them into the main query instead of firing one- # extra SELECT per source — the reverse 1:1 was an unprefetched N+1 that dominated the- # list load (up to one query, and a get_or_create write, per source).- .select_related("created_by", "revenue_analytics_config")- .prefetch_related(- latest_completed_job_prefetch(self.team_id, "jobs", to_attr="ordered_jobs"),- # The one place schemas are read during serialization. `active_schemas` used to be a- # second prefetch over the same rows — it's now derived in Python from this one (see- # `_active_schemas`), so the schema table is scanned once.- Prefetch(- "schemas",- queryset=ExternalDataSchema.objects.filter(team_id=self.team_id)- .exclude(deleted=True)- .select_related(*schema_select)- .order_by("name"),- ),- )- .order_by(self.ordering)- )-- def _resolve_stored_credential(self, source_type: str, payload: dict) -> ResolvedStoredCredential:- """Merge a connect-link stored credential into `payload` when it carries a `credential_id`.-- Lets the create and setup flows reference credentials the user entered on the connect page- instead of passing secrets inline. Only credentials the requesting user stored resolve —- ids are listable within a team, so without the owner check any member could consume a- teammate's stashed secrets into a source they control. Returns the (possibly merged)- payload, the resolved credential (which the caller deletes once consumed — stored- credentials are single-use), and a 400 Response to return as-is on a lookup miss or- source-type mismatch.- """- credential_id = payload.pop("credential_id", None)- if credential_id is None:- return ResolvedStoredCredential(payload=payload, credential=None, error_response=None)- try:- credential = PendingSourceCredential.objects.for_team(self.team_id).get(- id=credential_id, created_by=cast(User, self.request.user), expires_at__gt=timezone.now()- )- except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):- return ResolvedStoredCredential(- payload=payload,- credential=None,- error_response=Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Stored credential '{credential_id}' not found or expired"},- ),- )- if credential.source_type != source_type:- return ResolvedStoredCredential(- payload=payload,- credential=None,- error_response=Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Stored credential '{credential_id}' is for "- f"'{credential.source_type}', not '{source_type}'"- },- ),- )- # Stored credentials win over inline keys so an agent can't override what the user entered.- return ResolvedStoredCredential(- payload={**payload, **credential.payload}, credential=credential, error_response=None- )-- @extend_schema(- request=ExternalDataSourceCreateSerializer, responses={201: ExternalDataSourceCreateResponseSerializer}- )- def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:- serializer = self.get_serializer(data=request.data)- serializer.is_valid(raise_exception=True)-- source_type = serializer.validated_data["source_type"]- payload = dict(serializer.validated_data["payload"] or {})-- secret_ref_response = _unresolved_secret_ref_response(payload)- if secret_ref_response is not None:- return secret_ref_response-- # A `credential_id` in the payload references connection details the user entered on the- # connect-link page — resolve it to the real secrets so `create` can target a specific- # `schemas` set (unlike `setup`, which discovers and enables every table).- resolved = self._resolve_stored_credential(source_type, payload)- if resolved.error_response is not None:- return resolved.error_response-- response = self._create_external_data_source(- request,- source_type=source_type,- payload=resolved.payload,- prefix=serializer.validated_data.get("prefix"),- description=serializer.validated_data.get("description"),- access_method=serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE),- created_via=serializer.validated_data.get("created_via", ExternalDataSource.CreatedVia.API),- direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),- destination_ids=serializer.validated_data.get("destination_ids"),- )- # Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.- if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:- resolved.credential.delete()- return response-- @extend_schema(- parameters=[- OpenApiParameter(- name="source_type",- type=str,- required=True,- description="The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').",- ),- OpenApiParameter(- name="integration_id",- type=int,- required=True,- description="The OAuth integration id whose accounts should be listed.",- ),- OpenApiParameter(- name="search",- type=str,- required=False,- description="Optional case-insensitive filter over account name/value, for sources whose "- "resource list is large (e.g. GitHub repositories).",- ),- ],- responses={200: IntegrationAccountsResponseSerializer},- )- @action(methods=["GET"], detail=False, url_path="oauth_accounts")- def oauth_accounts(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """List the accounts/properties a connected OAuth integration exposes, in the shared- IntegrationAccount shape. The logic lives in each source (via OAuthMixin.get_oauth_accounts);- this endpoint just routes by source type, applies the optional search filter, and serializes."""- source_type = request.query_params.get("source_type")- integration_id = request.query_params.get("integration_id")- search = request.query_params.get("search") or None- if not source_type or not integration_id:- raise ValidationError("source_type and integration_id are required")-- try:- integration_id_int = int(integration_id)- except ValueError:- raise ValidationError("integration_id must be an integer")-- try:- source = SourceRegistry.get_source(cast(ExternalDataSourceType, source_type))- except ValueError:- raise ValidationError(f"Unknown source type: {source_type}")-- if not isinstance(source, OAuthMixin):- raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")-- # The integration id is caller-supplied and each source looks it up by (id, team_id) only, so- # without this a same-team integration of a different provider would be accepted here and its- # OAuth token handed to this source's provider. Pin it to the kind(s) the source's picker- # declares before any of that runs.- expected_kinds = get_oauth_integration_kinds(source.get_source_config.fields)- if not expected_kinds:- raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")- if not Integration.objects.filter(- id=integration_id_int, team_id=self.team_id, kind__in=expected_kinds- ).exists():- # One message for "gone" and "wrong kind" alike: from the UI both mean the picker is holding- # a connection this source can't use, and neither tells the caller anything about ids it- # isn't already allowed to see.- raise ValidationError(- f"No {source_type} connection was found for this integration. Please reconnect the integration."- )-- cache_key = f"oauth_accounts/{self.team_id}/{source_type}/{integration_id_int}/{search or ''}"- cached = cache.get(cache_key)- if cached is not None:- return Response(cached)-- try:- accounts = source.get_oauth_accounts(integration_id_int, self.team_id, search=search)- except NotImplementedError:- # An OAuth source that hasn't implemented account listing yet (passes the isinstance check).- raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")- except IntegrationAccountListingError as e:- # Actionable, customer-side failure (revoked/expired token, deleted integration, the provider- # rejecting the credentials) — surface the message as a 400. Anything else (e.g. a bare- # ValueError from an internal bug) stays uncaught and becomes a 500 so monitors see it.- raise ValidationError(str(e))-- # Belt-and-suspenders: sources that support server-side search already return matching results;- # this filters sources that returned a full list and ignored `search`.- accounts = filter_integration_accounts(accounts, search)- response_data = {"accounts": IntegrationAccountSerializer(accounts, many=True).data}- # Don't cache an empty result: a transient provider hiccup that returns [] without raising would- # otherwise poison the picker for 60s for every admin on the team.- if accounts:- cache.set(cache_key, response_data, 60)- return Response(response_data)-- def perform_update(self, serializer: serializers.BaseSerializer) -> None:- # Runs for both PUT and PATCH (DRF's partial_update delegates to update -> perform_update).- # `created_via` is write-once and reflects original creation origin; the edit's own origin- # comes from the request-derived `source` that report_user_action attaches.- super().perform_update(serializer)- instance = cast(ExternalDataSource, serializer.instance)- report_user_action(- cast(User, self.request.user),- "data warehouse source updated",- {- "source_type": instance.source_type,- "created_via": instance.created_via,- "source_id": str(instance.pk),- },- team=self.team,- request=self.request,- )-- def _create_external_data_source(- self,- request: Request,- *,- source_type: str,- payload: dict,- prefix: str | None,- description: str | None,- access_method: str,- created_via: str,- direct_query_enabled: bool = False,- skip_credential_validation: bool = False,- destination_ids: list | None = None,- ) -> Response:- # `skip_credential_validation` is set only by the `setup` action, which has already run the- # full config + credential gate (including the SSRF host check) before discovering schemas.- # It avoids a second live credential round-trip — and the confusing failure mode where the- # first check passes but a transient blip fails the second, leaving nothing created.-- # The setup wizard and PostHog's agent surfaces drive creation through the MCP tools, which- # inject `created_via=mcp` before the request reaches us — the agent can't set the field- # itself. Upgrade that machine-injected value when the transport identifies one of them, so- # their runs are distinguishable from other MCP clients. Explicit `web`/`api` values are- # left alone. The PostHog apps and the headless agents all map to `self_driving`: the- # distinction between them is an analytics one, and splitting it here would need a new- # stored value.- if created_via == ExternalDataSource.CreatedVia.MCP:- transport_created_via = {- EventSource.WIZARD: ExternalDataSource.CreatedVia.WIZARD,- EventSource.DESKTOP: ExternalDataSource.CreatedVia.SELF_DRIVING,- EventSource.MOBILE: ExternalDataSource.CreatedVia.SELF_DRIVING,- EventSource.POSTHOG_CODE: ExternalDataSource.CreatedVia.SELF_DRIVING,- EventSource.SELF_DRIVING: ExternalDataSource.CreatedVia.SELF_DRIVING,- }- created_via = transport_created_via.get(get_event_source(request), created_via)- # The wizard's `self-driving` onboarding program shares the generic `posthog/wizard`- # transport but marks its UA distinctly — attribute its sources as self_driving too, so- # a source connected during a self-driving run isn't lumped in with plain wizard setups.- if created_via == ExternalDataSource.CreatedVia.WIZARD and is_wizard_self_driving_program(request):- created_via = ExternalDataSource.CreatedVia.SELF_DRIVING- is_direct_query = access_method == ExternalDataSource.AccessMethod.DIRECT-- if ExternalDataSource.is_system_managed_prefix(prefix):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": RESERVED_SOURCE_NAME_MESSAGE},- )-- if is_direct_query and source_type not in direct_capable_source_types():- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},- )-- if is_direct_query:- prefix = prefix.strip() if isinstance(prefix, str) else ""- if not prefix:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Name is required for direct query sources"},- )- else:- is_valid, error_message = validate_source_prefix(prefix)- if not is_valid:- raise ValidationError(error_message)-- if not prefix:- if self.prefix_required(source_type):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": "You already have a source of this type. Add a table prefix so this connection's tables don't clash with your existing source."- },- )- elif self.prefix_exists(source_type, prefix):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Another source of this type already uses the prefix '{prefix}'. Choose a different prefix so this connection's tables don't clash."- },- )-- if access_method == ExternalDataSource.AccessMethod.WAREHOUSE and is_any_external_data_schema_paused(- self.team_id- ):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},- )-- # Strip leading and trailing whitespace- if payload is not None:- for key, value in payload.items():- if isinstance(value, str):- payload[key] = value.strip()- source_type_model = ExternalDataSourceType(source_type)- source = SourceRegistry.get_source(source_type_model)- if not is_direct_query and not source.supports_scheduled_sync:- return Response(- ExternalDataSourceErrorResponseSerializer(- {"message": f"{source_type_model.label} is available only as a direct connection."}- ).data,- status=status.HTTP_400_BAD_REQUEST,- )- max_instances = source.max_instances_per_team- if max_instances is not None and count_active_sources(self.team_id, source_type_model) >= max_instances:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"You can create at most {max_instances} sources of this type per project."},- )- if skip_credential_validation:- source_config: Config = source.parse_config(payload)- else:- error_response, validated_config = self._validate_source_config_and_credentials(- source, source_type_model, payload, access_method=access_method- )- if error_response is not None or validated_config is None:- return error_response or Response(status=status.HTTP_400_BAD_REQUEST)- source_config = validated_config-- new_source_model = ExternalDataSource.objects.create(- source_id=str(uuid.uuid4()),- connection_id=str(uuid.uuid4()),- destination_id=str(uuid.uuid4()),- created_by=request.user if isinstance(request.user, User) else None,- created_via=created_via,- team=self.team,- status="Running",- source_type=source_type_model,- api_version=source.default_version,- job_inputs=source_config.to_dict(),- prefix=prefix,- description=description,- access_method=access_method,- direct_query_enabled=direct_query_enabled,- )-- # Post-create hook (Custom claims its bound OAuth2 integration row here). No-op otherwise.- source.on_source_created(new_source_model, self.team_id)-- # CDC: gate per-source-type adapter availability up front so downstream blocks- # can `if cdc_enabled` without repeating the source-type check.- try:- cdc_adapter: CDCSourceAdapter | None = get_cdc_adapter(new_source_model)- except ValueError:- cdc_adapter = None- cdc_enabled = (- payload.get("cdc_enabled", False) and cdc_adapter is not None and is_cdc_enabled_for_team(self.team)- )-- try:- source_schemas = source.get_schemas(- source_config, self.team_id, api_version=source.resolve_api_version(new_source_model.api_version)- )- except NotImplementedError:- # Source doesn't implement schema discovery (e.g. an unreleased scaffold the UI hides).- # Roll back the row just created so a caller can't accumulate orphaned sources, and return- # a clean 400 instead of the uncaught 500 this would otherwise raise. Mirrors `setup`.- new_source_model.delete()- # nosemgrep: api-response-must-match-schema -- conventional error message, not a schema-bound payload- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": _source_unavailable_message(source_type)},- )- except Exception as e:- # `get_schemas` opens its own connection, so credentials validated above can still fail- # here (e.g. a BigQuery service account key rotated/revoked in between). Classify via- # the source's own non-retryable-error map, same as `database_schema` and- # `refresh_schemas`, and roll back the row so a source that can't discover its schema- # doesn't linger half-created.- error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)- if not is_expected_source_error:- capture_exception(- e,- {- "source_type": source_type,- "team_id": self.team_id,- "source_id": str(new_source_model.id),- },- )- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": error_message},- )- if is_direct_query:- new_source_model.connection_metadata = get_direct_connection_metadata(- source_impl=source,- source_config=source_config,- team_id=self.team_id,- source_model=new_source_model,- )- new_source_model.save(update_fields=["connection_metadata", "updated_at"])- source_schemas_by_name = {schema.name: schema for schema in source_schemas}- schema_names = [schema.name for schema in source_schemas]- source_config_dict = source_config.to_dict()- default_source_schema = source_config_dict.get("schema")- default_source_catalog = source_config_dict.get("database") or source_config_dict.get("catalog")- schema_label_by_name = {s.name: s.label for s in source_schemas}-- # Omitting `schemas` means "sync what you found", the same defaults `setup` builds. A- # caller that wants to hand-pick tables still sends the array; one that just has- # credentials no longer has to run schema discovery itself to write back what we already- # know. Discovery ran above, so the defaults cost nothing extra here.- payload_schemas = payload.get("schemas")- if payload_schemas is not None and not isinstance(payload_schemas, list):- new_source_model.delete()- return Response(- data={"message": "The 'schemas' field must be a list of the tables to sync."},- status=status.HTTP_400_BAD_REQUEST,- )- if not payload_schemas:- payload_schemas = build_default_schemas(source_schemas)-- # Return 400 if we get any schema names that don't exist in our source- if any(schema.get("name") not in schema_names for schema in payload_schemas):- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Schemas given do not exist in source"},- )-- # Refuse per-schema `sync_type=cdc` when source-level CDC is off — `_setup_cdc_resources`- # would be skipped, leaving the source with no replication slot/publication.- if not cdc_enabled:- cdc_schemas_in_payload = sorted(- {- schema["name"]- for schema in payload_schemas- if schema.get("sync_type") == "cdc"- and schema.get("should_sync", False)- and isinstance(schema.get("name"), str)- }- )- if cdc_schemas_in_payload:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": (- "CDC must be enabled on the source before selecting it as a sync type. "- f"The following schemas requested CDC: {', '.join(cdc_schemas_in_payload)}."- )- },- )-- active_schemas: list[ExternalDataSchema] = []-- # Pre-fetch PK column names for CDC tables- pk_columns_by_table: dict[str, list[str]] = {}- if cdc_enabled:- cdc_table_names_by_schema: dict[str, set[str]] = {}- cdc_schema_name_by_location: dict[tuple[str, str], str] = {}- for schema in payload_schemas:- if schema.get("sync_type") != "cdc" or not schema.get("should_sync", False):- continue-- schema_name = schema.get("name")- if not isinstance(schema_name, str):- continue-- _, resolved_source_schema, resolved_source_table_name = get_postgres_source_table_location(- schema_name=schema_name,- source_schema=source_schemas_by_name.get(schema_name),- default_schema=default_source_schema,- )- cdc_table_names_by_schema.setdefault(resolved_source_schema, set()).add(resolved_source_table_name)- cdc_schema_name_by_location[(resolved_source_schema, resolved_source_table_name)] = schema_name-- if cdc_table_names_by_schema:- try:- with cdc_pg_connection(new_source_model) as conn:- for db_schema, cdc_table_names in cdc_table_names_by_schema.items():- queried_pks = get_primary_key_columns(conn, db_schema, list(cdc_table_names))- for table_name, primary_key_columns in queried_pks.items():- schema_name = cdc_schema_name_by_location.get((db_schema, table_name))- if schema_name is not None:- pk_columns_by_table[schema_name] = primary_key_columns- except _EXPECTED_CONNECTION_ERRORS as e:- # Connecting to the user's database to detect CDC primary keys is expected to- # fail when the host, port, credentials, or SSH tunnel are wrong, or the server- # requires/refuses SSL. Surface it as a 400, but don't capture it — these are- # user/upstream connection problems, not bugs in our code, and capturing every- # one floods error tracking. Mirrors the CDC-prerequisite handlers below.- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to your database to set up change data capture: {e}"},- )-- # CDC needs a PK for UPDATE/DELETE merges. Refuse here so `_setup_cdc_resources` doesn't- # create replication state on the source for a config we're about to reject.- tables_missing_pk = sorted(- {- schema["name"]- for schema in payload_schemas- if schema.get("sync_type") == "cdc"- and schema.get("should_sync", False)- and isinstance(schema.get("name"), str)- and not pk_columns_by_table.get(schema["name"])- }- )- if tables_missing_pk:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": (- "CDC requires a primary key on each table. "- f"The following tables have no primary key: {', '.join(tables_missing_pk)}."- )- },- )-- # Engine-side CDC resource setup runs after PK validation so we don't leave- # replication state on the source for a config we're about to refuse.- if cdc_enabled:- assert cdc_adapter is not None # narrowed by `cdc_enabled`- cdc_error = self._setup_cdc_resources(cdc_adapter, new_source_model, payload)- if cdc_error is not None:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": cdc_error},- )-- # Direct-query table materialization is engine-specific; dispatch on the engine, not the- # source type. None for non-direct-capable sources.- direct_engine_adapter = get_direct_query_engine(new_source_model.direct_engine)-- # Create all ExternalDataSchema objects and enable syncing for active schemas- for schema in payload_schemas:- sync_type = schema.get("sync_type")- requires_incremental_fields = sync_type == "incremental" or sync_type == "append"- incremental_field = schema.get("incremental_field")- incremental_field_type = schema.get("incremental_field_type")- primary_key_columns = schema.get("primary_key_columns")- sync_time_of_day = schema.get("sync_time_of_day")- should_sync = schema.get("should_sync", False)- payload_enabled_columns = schema.get("enabled_columns")- if isinstance(payload_enabled_columns, list):- # `[]` and `None` are distinct: `None` means sync all columns, `[]` means- # sync only the always-retained PK + incremental field.- enabled_columns: list[str] | None = [- str(column) for column in payload_enabled_columns if isinstance(column, str)- ]- else:- enabled_columns = None-- payload_row_filters = schema.get("row_filters")- row_filters: list[dict[str, Any]] | None = (- payload_row_filters if isinstance(payload_row_filters, list) and payload_row_filters else None- )-- if should_sync and requires_incremental_fields and incremental_field is None:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Incremental schemas given do not have an incremental field set"},- )-- if should_sync and requires_incremental_fields and incremental_field_type is None:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Incremental schemas given do not have an incremental field type set"},- )-- schema_name = schema.get("name")- source_schema = source_schemas_by_name.get(schema_name)-- metadata_source_catalog: str | None- metadata_source_schema: str | None- metadata_source_table_name: str | None- # Direct mode needs a resolved source location for the live-query table; warehouse mode- # keeps storing whatever the source reported to avoid changing sync routing (except- # Postgres, which resolves in both modes — carried by the adapter flag).- if direct_engine_adapter is not None and (- is_direct_query or direct_engine_adapter.resolves_location_in_warehouse_mode- ):- metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (- direct_engine_adapter.source_table_location(- schema_name=schema_name,- source_schema=source_schema,- default_schema=default_source_schema,- default_catalog=default_source_catalog,- )- )- else:- metadata_source_catalog = source_schema.source_catalog if source_schema else None- metadata_source_schema = source_schema.source_schema if source_schema else None- metadata_source_table_name = source_schema.source_table_name if source_schema else None-- schema_metadata = (- sql_schema_metadata(- source_schema.columns if source_schema else [],- source_schema.foreign_keys if source_schema else [],- source_catalog=metadata_source_catalog,- source_schema=metadata_source_schema,- source_table_name=metadata_source_table_name,- )- if source.supports_column_selection- else {}- )- # Sources that namespace tables outside SQL schemas (e.g. GitHub repos) attach their- # own location keys on the discovered schema; persist them so sync-time resolution- # never depends on parsing the row name.- if source_schema is not None and source_schema.schema_metadata:- schema_metadata = {**schema_metadata, **source_schema.schema_metadata}-- if row_filters is not None:- # Only sources that push filters into their query (SQL WHERE) can honor them — a- # saved-but-ignored filter would silently sync unfiltered rows.- if not source.supports_row_filters:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Row filter not allowed for schema '{schema_name}': "- "row filters are not supported for this source type."- },- )- if reason := unsupported_row_filter_reason(- is_direct_query=new_source_model.is_direct_query, is_cdc=sync_type == "cdc"- ):- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Row filter not allowed for schema '{schema_name}': {reason}"},- )- try:- validate_and_coerce_row_filters(row_filters, schema_metadata)- except RowFilterValidationError as e:- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid row filter for schema '{schema_name}': {e}"},- )-- is_cdc_schema = sync_type == "cdc"- # A CDC table the user isn't enabling hasn't been "set up" — leave its sync method- # blank so the schemas UI prompts the user to configure it before it can sync, rather- # than presetting `cdc` on every discovered table. Only tables the user actively- # enables get a concrete CDC method + config.- cdc_not_set_up = is_cdc_schema and not should_sync- if requires_incremental_fields and new_source_model.supports_scheduled_sync:- # If the caller didn't provide primary_key_columns, fall back to whatever the- # source detected during schema discovery. Otherwise we rely on sync-time- # re-detection, which can disagree with discovery (e.g. permissions differences- # across query paths) and leave incremental syncs without a primary key.- effective_primary_key_columns = primary_key_columns or (- source_schema.detected_primary_keys if source_schema else None- )- # Lookback only applies to incremental (merge-by-PK makes the overlap re-read idempotent).- # Mirror the schema-update path's IntegerField(min_value=0, max_value=5_184_000) so both- # creation paths reject the same inputs instead of silently dropping null/float values.- lookback_seconds = schema.get("incremental_field_lookback_seconds")- # When the caller didn't set a lookback, fall back to the source-defined default- # (e.g. Google Ads stats tables, whose recent rows Google keeps revising for days).- # This loop is the single creation choke point, so the default reaches both the- # wizard and one-shot flows; it's then validated by the bounds check just below.- if lookback_seconds is None and source_schema is not None:- lookback_seconds = source_schema.default_incremental_lookback_seconds- if lookback_seconds is not None:- # Coerce whole-number floats (e.g. 90.0) the way DRF's IntegerField does.- if isinstance(lookback_seconds, float) and lookback_seconds.is_integer():- lookback_seconds = int(lookback_seconds)- # bool is an int subclass — exclude it so true/false aren't treated as 1/0.- is_valid_int = isinstance(lookback_seconds, int) and not isinstance(lookback_seconds, bool)- if not is_valid_int or not (0 <= lookback_seconds <= 5_184_000):- new_source_model.delete()- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"incremental_field_lookback_seconds must be an integer between 0 and 5184000 (60 days) for schema '{schema_name}'."- },- )- # Canonicalize the incremental field against what the source declares for this- # endpoint: discovery surfaces both a display `label` and the underlying `field`- # (e.g. Stripe's label "created_at" -> field "created"), and API callers regularly- # send the label — which then fails every sync with a missing-column error. Match on- # either and persist the declared field + its real field_type.- if incremental_field is not None and source_schema is not None:- for declared in source_schema.incremental_fields:- if incremental_field in (declared["field"], declared["label"]):- incremental_field = declared["field"]- incremental_field_type = str(declared["field_type"])- break-- sync_type_config = {- "incremental_field": incremental_field,- "incremental_field_type": incremental_field_type,- "schema_metadata": schema_metadata,- **({"primary_key_columns": effective_primary_key_columns} if effective_primary_key_columns else {}),- **(- {"incremental_field_lookback_seconds": lookback_seconds}- if sync_type == "incremental" and lookback_seconds is not None- else {}- ),- }- elif is_cdc_schema and not cdc_not_set_up:- cdc_table_mode = schema.get("cdc_table_mode", "consolidated")- sync_type_config = {- "cdc_mode": "snapshot",- "primary_key_columns": pk_columns_by_table.get(schema_name, []),- "schema_metadata": schema_metadata,- "cdc_table_mode": cdc_table_mode,- }- else:- sync_type_config = {"schema_metadata": schema_metadata}-- # CDC schemas benefit from a tighter poll cadence — the extraction workflow is cheap- # and the value prop is near-real-time. Other sync types use the 6h default.- schema_sync_frequency_interval = (- timedelta(minutes=5)- if is_cdc_schema and not cdc_not_set_up and new_source_model.supports_scheduled_sync- else timedelta(hours=6)- )- schema_model = ExternalDataSchema.objects.create(- name=schema_name,- team=self.team,- source=new_source_model,- should_sync=should_sync,- sync_type=(None if cdc_not_set_up else sync_type) if new_source_model.supports_scheduled_sync else None,- sync_time_of_day=sync_time_of_day if new_source_model.supports_scheduled_sync else None,- sync_type_config=sync_type_config,- description=source_schema.description if source_schema else None,- label=schema_label_by_name.get(schema_name),- sync_frequency_interval=schema_sync_frequency_interval,- enabled_columns=enabled_columns,- row_filters=row_filters,- )-- # The CDC path is Postgres-only, and the engine adapter's `source_table_location`- # guarantees non-None schema/table when it resolves above. `cast` narrows for mypy- # without a runtime check. The adapter no-ops for self-managed / no-publication.- if is_cdc_schema and should_sync and cdc_enabled and cdc_adapter is not None:- cdc_adapter.add_table(- new_source_model,- cast(str, metadata_source_schema),- cast(str, metadata_source_table_name),- )-- if direct_engine_adapter is not None and is_direct_query and should_sync:- # Apply the picker's column subset on the very first DataWarehouseTable build,- # not just on subsequent updates — otherwise users see all columns in HogQL until- # they hit save again or a refresh runs. Columns are keyed by raw, case-sensitive- # source names (`normalize=False`).- schema_model.table = direct_engine_adapter.upsert_table(- None,- schema_name=schema_name,- source=new_source_model,- columns=filter_dwh_columns_by_enabled_columns(- direct_engine_adapter.columns_to_dwh_columns(source_schema.columns if source_schema else []),- enabled_columns,- source_schema.detected_primary_keys if source_schema else None,- incremental_field,- normalize=False,- ),- source_catalog=metadata_source_catalog,- source_schema=cast(str, metadata_source_schema),- source_table_name=cast(str, metadata_source_table_name),- )- schema_model.save(update_fields=["table"])-- if should_sync and new_source_model.supports_scheduled_sync:- active_schemas.append(schema_model)-- # Attach destinations before any schedule starts. Extraction snapshots the set onto the- # run, so a source whose destinations arrive after its first sync began writes that run- # to the warehouse alone, and reaching the others costs a full resync.- if destination_ids:- try:- set_source_destinations(- team_id=self.team_id,- source_id=new_source_model.pk,- destination_ids=destination_ids,- )- except Exception as e:- # The source is already created and its tables are configured. Losing that over a- # destination set the user can still fix on the Destinations tab is the worse trade.- logger.exception(- "Could not attach destinations to a new source",- exc_info=e,- source_id=new_source_model.pk,- )-- # Create all sync schedules over a single shared Temporal connection. Creating them- # one call at a time reconnects to Temporal on every iteration, which does not scale- # to sources with thousands of schemas (e.g. a Slack workspace with thousands of- # channels).- try:- schedule_errors = bulk_create_external_data_job_schedules(- [(active_schema, active_schema.should_sync) for active_schema in active_schemas]- )- for schema_id, schedule_error in schedule_errors:- # The source model was already created, so a partial schedule failure- # shouldn't fail the request — log each failure and carry on.- logger.exception(- "Could not trigger external data job",- exc_info=schedule_error,- schema_id=schema_id,- )- except Exception as e:- logger.exception("Could not trigger external data job", exc_info=e)-- # Per-source schema discovery schedule. Runs every 6h so newly added- # upstream resources (Slack channels, Postgres tables, …) get picked up- # without re-discovering on every per-schema sync tick. Direct-query- # sources resolve schemas at query time, so they opt out of all- # background sync — including this discovery cadence.- if new_source_model.supports_scheduled_sync:- try:- sync_discover_schemas_schedule(new_source_model, create=True)- except Exception as e:- logger.exception("Could not create schema discovery schedule", exc_info=e)-- # Start CDC extraction schedule if any CDC schemas are active- if cdc_enabled:- try:- sync_cdc_extraction_schedule(new_source_model, create=True)- ensure_cdc_slot_cleanup_schedule()- except Exception as e:- logger.exception("Could not create CDC schedules", exc_info=e)-- if new_source_model.revenue_analytics_config_safe.enabled:- managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(- team=self.team,- kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,- )- managed_viewset.sync_views()- ensure_person_join(self.team.pk, new_source_model.prefix)-- # `source` (web/api/mcp/wizard/posthog_code) is derived from the request by report_user_action;- # `created_via` is the caller's explicit intent (with one exception: the machine-injected `mcp`- # is upgraded above when the transport identifies the wizard or PostHog Desktop). They usually- # agree but are kept separate so a transport change (e.g. a new wrapper UA) doesn't silently- # rewrite historical attribution.- report_user_action(- cast(User, request.user),- "data warehouse source created",- {- "source_type": source_type,- "created_via": created_via,- "source_access_method": access_method,- "direct_query_enabled": direct_query_enabled,- "schema_count": len(active_schemas),- "source_id": str(new_source_model.pk),- },- team=self.team,- request=request,- )-- return Response(status=status.HTTP_201_CREATED, data={"id": new_source_model.pk})-- def _setup_cdc_resources(- self, adapter: CDCSourceAdapter, source_model: ExternalDataSource, payload: dict- ) -> str | None:- """Provision CDC for an existing source by delegating to the engine adapter.-- Writes universal CDC fields (mode, lag thresholds, auto-drop policy) plus the- adapter-supplied resource fields (slot/publication identifiers, consistent- point, …) into ``source_model.job_inputs`` and saves. Returns an error string- on failure, or None on success. Callers decide whether to delete the source- on failure (create flow does; enable_cdc does not).- """- management_mode = payload.get("cdc_management_mode", "posthog")- logger.info(- "Setting up CDC resources for source",- source_id=str(source_model.pk),- source_type=source_model.source_type,- management_mode=management_mode,- )-- resource_fields, error = adapter.setup_resources(source_model, payload)- if error is not None:- logger.warning(- "CDC resource setup failed",- source_id=str(source_model.pk),- source_type=source_model.source_type,- management_mode=management_mode,- error=error,- )- return error-- logger.info(- "CDC resources provisioned",- source_id=str(source_model.pk),- management_mode=management_mode,- slot_name=resource_fields.get("cdc_slot_name"),- publication_name=resource_fields.get("cdc_publication_name"),- resource_keys=sorted(resource_fields.keys()),- )-- job_inputs = dict(source_model.job_inputs or {})- job_inputs.update(- {- "cdc_enabled": True,- "cdc_auto_drop_slot": payload.get("cdc_auto_drop_slot", True),- "cdc_lag_warning_threshold_mb": payload.get(- "cdc_lag_warning_threshold_mb", DEFAULT_LAG_WARNING_THRESHOLD_MB- ),- "cdc_lag_critical_threshold_mb": payload.get(- "cdc_lag_critical_threshold_mb", DEFAULT_LAG_CRITICAL_THRESHOLD_MB- ),- }- )- job_inputs.update(resource_fields)- source_model.job_inputs = job_inputs- source_model.save(update_fields=["job_inputs", "updated_at"])- return None-- def prefix_required(self, source_type: str) -> bool:- # A prefix is only needed when a no-prefix source of the same type already- # exists. Two no-prefix sources would write to the same table names; sources- # with distinct prefixes (including one no-prefix + N prefixed) have separate- # table namespaces and cannot collide.- no_prefix_source_exists = (- ExternalDataSource.objects.exclude(deleted=True)- .filter(team_id=self.team.pk, source_type=source_type)- .filter(Q(prefix__isnull=True) | Q(prefix=""))- .exists()- )- return no_prefix_source_exists-- def prefix_exists(self, source_type: str, prefix: str) -> bool:- prefix_exists = (- ExternalDataSource.objects.exclude(deleted=True)- .filter(team_id=self.team.pk, source_type=source_type, prefix=prefix)- .exists()- )- return prefix_exists-- def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:- instance: ExternalDataSource = self.get_object()-- schemas = list(- ExternalDataSchema.objects.exclude(deleted=True)- .filter(team_id=self.team_id, source_id=instance.id)- .select_related("table")- .all()- )-- # Deleting the source deletes every table it synced, so it needs editor on each of them.- self._assert_can_write_schemas(schemas)-- # Soft-delete source, schemas, tables, and companion _cdc tables atomically- # first so DB state is consistent even if the external cleanup below fails- with transaction.atomic():- for schema in schemas:- if schema.table:- schema.table.soft_delete()-- # Bulk soft-delete the schema rows in a single UPDATE. Per-row soft_delete()- # runs a SELECT + UPDATE + activity-log write each, which does not scale to- # sources with thousands of schemas (e.g. a Slack workspace with thousands of- # channels).- deleted_at = datetime.now(UTC)- ExternalDataSchema.objects.filter(team_id=self.team_id, id__in=[schema.id for schema in schemas]).update(- deleted=True, deleted_at=deleted_at- )- # Mirror the bulk update onto the in-memory objects so the post-atomic- # `schema.delete_table()` save() below doesn't overwrite deleted=True with the- # stale in-memory value.- for schema in schemas:- schema.deleted = True- schema.deleted_at = deleted_at-- # Clean up CDC companion tables (e.g. {name}_cdc) — these are standalone- # DataWarehouseTable records linked to the source but not to schema.table.- DataWarehouseTable.objects.filter(- external_data_source_id=instance.id,- team_id=self.team_id,- deleted=False,- ).exclude(id__in=[s.table_id for s in schemas if s.table_id is not None]).update(deleted=True)-- instance.soft_delete()-- # Best-effort webhook cleanup — soft-deletes are already committed- source_type = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type)- if isinstance(source, WebhookSource) and instance.job_inputs:- try:- config = source.parse_config(instance.job_inputs)- delete_webhook_and_hog_function(- team=self.team,- source=source,- config=config,- source_id=str(instance.pk),- api_version=source.resolve_api_version(instance.api_version),- )- except Exception as e:- capture_exception(e)-- # Best-effort external cleanup — soft-deletes are already committed- latest_running_job = (- ExternalDataJob.objects.filter(pipeline_id=instance.pk, team_id=instance.team_id)- .order_by("-created_at")- .first()- )- if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":- cancel_external_data_workflow(latest_running_job.workflow_id)-- # Delete all schema sync schedules over a single shared Temporal connection — see- # the matching comment in `create`. Guarded so a Temporal-connect failure here- # doesn't skip the source/discovery schedule and S3 cleanup below.- try:- schedule_delete_errors = bulk_delete_external_data_schedules([str(schema.id) for schema in schemas])- for schema_id, schedule_delete_error in schedule_delete_errors:- capture_exception(schedule_delete_error, {"schema_id": schema_id})- except Exception as e:- capture_exception(e)-- for schema in schemas:- try:- schema.delete_table()- except Exception as e:- capture_exception(e)-- try:- delete_external_data_schedule(str(instance.id))- except Exception as e:- capture_exception(e)-- try:- delete_discover_schemas_schedule(str(instance.id))- except Exception as e:- capture_exception(e)-- return Response(status=status.HTTP_204_NO_CONTENT)-- @action(methods=["POST"], detail=True)- def reload(self, request: Request, *args: Any, **kwargs: Any):- instance: ExternalDataSource = self.get_object()-- if instance.is_direct_query:- return self.refresh_schemas(request, *args, **kwargs)-- # Syncs every enabled schema, so it needs editor on each - a table locked below the source- # would otherwise be refreshed here, and for a full refresh that drops and reloads it.- self._assert_can_write_schemas(- ExternalDataSchema.objects.filter(team_id=self.team_id, source_id=instance.id, should_sync=True)- .exclude(deleted=True)- .select_related("source", "table")- )-- if is_any_external_data_schema_paused(self.team_id):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},- )-- try:- trigger_external_data_source_workflow(instance)-- except temporalio.service.RPCError:- # if the source schedule has been removed - trigger the schema schedules- instance.reload_schemas()-- except Exception as e:- logger.exception("Could not trigger external data job", exc_info=e)- raise-- instance.status = "Running"- instance.save()- return Response(status=status.HTTP_200_OK)-- @action(methods=["POST"], detail=True)- @extend_schema(- responses={- 200: {- "type": "object",- "properties": {- "added": {"type": "integer"},- "deleted": {"type": "integer"},- "auto_enabled": {"type": "integer"},- "total_tables_seen": {"type": "integer"},- },- }- }- )- def refresh_schemas(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Fetch current schema/table list from the source and create any new ExternalDataSchema rows (no data sync)."""- instance: ExternalDataSource = self.get_object()- logger.debug(- "refresh_schemas called",- source_id=str(instance.id),- team_id=self.team_id,- source_type=instance.source_type,- )- if not instance.job_inputs:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Source has no configuration."},- )- source: AnySource | None = None- try:- source_type = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type)- config = source.parse_config(instance.job_inputs)- # Explicit user action — bypass any cached schema discovery so newly added- # upstream resources (e.g. Slack channels) appear immediately.- schemas = source.get_schemas(- config, self.team_id, force_refresh=True, api_version=source.resolve_api_version(instance.api_version)- )- connection_metadata = (- get_direct_connection_metadata(- source_impl=source,- source_config=config,- team_id=self.team_id,- source_model=instance,- fallback=instance.connection_metadata,- )- if instance.is_direct_query- else instance.connection_metadata- )- schema_names = {s.name: s.label for s in schemas}- logger.info(- "refresh_schemas fetched from source",- source_id=str(instance.id),- schema_count=len(schema_names),- schema_names=schema_names,- )- except Exception as e:- error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)- logger.exception(- "Could not fetch schemas from source",- exc_info=e,- source_id=str(instance.id),- team_id=self.team_id,- source_type=instance.source_type,- error_type=type(e).__name__,- is_expected_source_error=is_expected_source_error,- )- if not is_expected_source_error:- capture_exception(- e,- {- "source_id": str(instance.id),- "source_type": instance.source_type,- "team_id": self.team_id,- "refresh_schemas": True,- },- )- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": error_message},- )-- descriptions = {s.name: s.description for s in schemas}- with transaction.atomic():- ExternalDataSource._base_manager.filter(pk=instance.pk).select_for_update().get()- if instance.is_direct_query and connection_metadata != instance.connection_metadata:- instance.connection_metadata = connection_metadata- instance.save(update_fields=["connection_metadata", "updated_at"])- # Migrate/dedupe legacy rows before sync_old_schemas; non-Postgres only once namespace cleared.- engine = get_direct_query_engine(instance.direct_engine)- name_substitutions = _refresh_name_substitutions(- engine, source=instance, source_schemas=schemas, team_id=self.team_id- )-- if name_substitutions:- schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}- descriptions = {- name_substitutions.get(name, name): description for name, description in descriptions.items()- }- # Namespaced-resource sources (GitHub) keep the legacy resource's rows bare alongside- # qualified rows for the others, so bare↔qualified tail matching would wrongly collapse- # them; match names exactly and seed per-resource location metadata on new rows.- namespaced_adapter = get_namespaced_resource_adapter(instance.source_type)- sync_result = sync_old_schemas_with_new_schemas(- schema_names,- source_id=str(instance.id),- team_id=self.team_id,- descriptions=descriptions,- strict_name_match=namespaced_adapter is not None and namespaced_adapter.uses_strict_schema_name_match,- schema_metadata_by_name=namespaced_adapter.schema_metadata_by_name(schemas)- if namespaced_adapter is not None- else None,- )- # Mutable local: engine reconciliation below may extend the deleted set.- schemas_deleted = sync_result.deleted-- if engine is not None:- reconciled_deleted_schemas = engine.reconcile_schemas(- source=instance, source_schemas=schemas, team_id=self.team_id- )- if reconciled_deleted_schemas:- schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})- elif isinstance(source, (SQLSource, ClickHouseSource)) and source.supports_column_selection:- # ClickHouse isn't a SQLSource but exposes the same column-selection- # capability and reconcile hook, so it reuses this path.- source.reconcile_schema_metadata(source=instance, source_schemas=schemas, team_id=self.team_id)-- # Outside the atomic block: schedule creation talks to Temporal, which must not run under- # the source row lock or against rows that could still roll back. `sync_result.created` holds- # post-substitution stored names, so remap the discovered names to match.- auto_enabled_names: list[str] = []- if sync_result.created:- source_schemas_by_name = {name_substitutions.get(s.name, s.name): s for s in schemas}- auto_enabled_names = auto_enable_new_schemas(instance, sync_result.created, source_schemas_by_name)-- logger.debug(- "refresh_schemas completed",- source_id=str(instance.id),- team_id=self.team_id,- added=len(sync_result.created),- deleted=len(schemas_deleted),- auto_enabled=len(auto_enabled_names),- total_tables_seen=len(schemas),- )- return Response(- status=status.HTTP_200_OK,- data={- "added": len(sync_result.created),- "deleted": len(schemas_deleted),- "auto_enabled": len(auto_enabled_names),- "total_tables_seen": len(schemas),- },- )-- @extend_schema(request=DatabaseSchemaRequestSerializer)- @action(methods=["POST"], detail=False)- def database_schema(self, request: Request, *arg: Any, **kwargs: Any):- source_type = request.data.get("source_type", None)-- if source_type is None:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Missing required parameter: source_type"},- )-- secret_ref_response = _unresolved_secret_ref_response(request.data)- if secret_ref_response is not None:- return secret_ref_response-- try:- source_type_model = ExternalDataSourceType(source_type)- except ValueError:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Unknown source_type '{source_type}'"},- )- source = SourceRegistry.get_source(source_type_model)- is_valid, errors = source.validate_config(request.data)- if not is_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid source config: {', '.join(errors)}"},- )- source_config: Config = source.parse_config(request.data)-- access_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)- try:- if isinstance(source, (PostgresSource, MySQLSource)):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config),- self.team_id,- access_method,- require_ssl=new_source_requires_ssl(source_config),- )- elif isinstance(source, CustomSource):- # Schema discovery for an as-yet-uncreated source: an integration-backed manifest may only use- # an unbound integration owned by the requester, or the probe could send another source's token- # to the submitted host.- credentials_valid, credentials_error = source.validate_credentials(- source_config, self.team_id, owner_user_id=self.request.user.id- )- else:- credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)- except Exception as e:- credentials_valid, credentials_error = _credentials_validation_failed(source, self.team_id, e)- if not credentials_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": credentials_error or INVALID_CREDENTIALS_FALLBACK_MESSAGE},- )-- try:- schemas = source.get_schemas(source_config, self.team_id)- except NotImplementedError:- # Source doesn't implement schema discovery (e.g. an unreleased source), so there are- # no tables to list — a caller mistake, not a server error worth capturing. Mirrors `setup`.- # nosemgrep: api-response-must-match-schema -- conventional error message, not a schema-bound payload- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": _source_unavailable_message(source_type)},- )- except Exception as e:- error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)- if not is_expected_source_error:- capture_exception(e, {"source_type": source_type, "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": error_message},- )-- # Best-effort per-endpoint scope probe — transient failure falls back to "available".- try:- endpoint_permissions = source.get_endpoint_permissions(- source_config, self.team_id, [schema.name for schema in schemas]- )- except Exception as e:- capture_exception(e, {"source_type": source_type, "team_id": self.team_id})- endpoint_permissions = {schema.name: None for schema in schemas}-- # Cache the CDC flag once: in non-DEBUG environments this calls posthoganalytics.feature_enabled,- # which makes a network round-trip per call. With large schema lists (e.g. Slack workspaces with- # thousands of channels) the per-iteration call inflated the response loop past the 120s gateway.- cdc_enabled = is_cdc_enabled_for_team(self.team)- # xmin is gated at the source-type level by the source's capability flag so it never- # leaks to another SQL source.- xmin_capable = source.supports_xmin- data = [- {- "table": schema.name,- "label": schema.label,- "should_sync": False,- "incremental_fields": schema.incremental_fields,- "incremental_available": schema.supports_incremental,- "append_available": schema.supports_append,- "cdc_available": schema.supports_cdc if cdc_enabled else None,- "xmin_available": schema.supports_xmin if xmin_capable else None,- "incremental_field": schema.incremental_fields[0]["field"]- if len(schema.incremental_fields) > 0 and len(schema.incremental_fields[0]["field"]) > 0- else None,- "sync_type": None,- "rows": schema.row_count,- "supports_webhooks": schema.supports_webhooks,- "webhook_only": schema.webhook_only,- "description": schema.description,- "should_sync_default": schema.should_sync_default,- "available_columns": [- {"field": col_name, "label": col_name, "type": col_type, "nullable": nullable}- for col_name, col_type, nullable in schema.columns- ],- "detected_primary_keys": schema.detected_primary_keys,- "permission_error": endpoint_permissions.get(schema.name),- "rls_warning": schema.rls_warning,- }- for schema in schemas- ]- return Response(status=status.HTTP_200_OK, data=data)-- @extend_schema(request=SourceSetupSerializer, responses={201: SourceSetupResponseSerializer})- @action(methods=["POST"], detail=False)- def setup(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """One-shot data warehouse source setup.-- Validate credentials, discover available tables, enable them all with sensible sync defaults- (incremental where supported, else append, else full refresh), and create the source in a single- call — the caller never has to assemble a `schemas` array. For sources that support webhooks- (e.g. Stripe), a webhook is auto-registered after creation: on success webhook-capable tables- switch to real-time webhook sync (unlocking webhook-only tables); on failure the polling- defaults stay in place. For fine-grained table/sync control, use the lower-level- `database_schema` + `create` flow instead.- """- # No database context needed here (unlike the read serializer), and skipping it avoids building- # the HogQL Database on this hot path.- serializer = SourceSetupSerializer(data=request.data)- serializer.is_valid(raise_exception=True)-- source_type = serializer.validated_data["source_type"]- payload = dict(serializer.validated_data.get("payload") or {})-- secret_ref_response = _unresolved_secret_ref_response(payload)- if secret_ref_response is not None:- return secret_ref_response-- resolved = self._resolve_stored_credential(source_type, payload)- if resolved.error_response is not None:- return resolved.error_response- # Mutable local: the CustomSource branch below rewrites payload keys before source creation.- payload = resolved.payload-- source_type_model = ExternalDataSourceType(source_type)- source = SourceRegistry.get_source(source_type_model)-- error_response, source_config = self._validate_source_config_and_credentials(source, source_type_model, payload)- if error_response is not None or source_config is None:- return error_response or Response(status=status.HTTP_400_BAD_REQUEST)-- if isinstance(source, CustomSource):- # Validation may have adopted static OAuth2 secrets into an integration row and rewritten- # the config to point at it. `_create_external_data_source` below re-parses the raw payload- # (it skips the credential gate), so propagate the rewrite onto the payload — the created- # source must store the row pointer, never the raw secrets.- validated_payload = source_config.to_dict()- for key in ("auth_oauth2_integration_id", "auth_oauth2_client_secret", "auth_oauth2_refresh_token"):- if validated_payload.get(key):- payload[key] = validated_payload[key]- else:- payload.pop(key, None)-- try:- source_schemas = source.get_schemas(source_config, self.team_id)- except NotImplementedError:- # Source doesn't implement schema discovery (e.g. an unreleased source) so it can't be- # set up via this one-shot flow — a caller mistake, not a server error worth capturing.- # nosemgrep: api-response-must-match-schema -- conventional error message, not a schema-bound payload- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": _source_unavailable_message(source_type)},- )- except Exception as e:- # Credentials validated above can still fail here — `get_schemas` opens its own- # connection — so classify via the source's non-retryable-error map, same as `create`,- # `database_schema`, and `refresh_schemas`, instead of surfacing the raw driver error.- error_message, is_expected_source_error = _classify_refresh_schemas_error(source, e)- if not is_expected_source_error:- capture_exception(e, {"source_type": source_type, "team_id": self.team_id})- return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": error_message})-- if not source_schemas:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "No tables found for this source. Check the credentials and permissions."},- )-- # Same best-effort per-table scope probe the schema picker runs, so one-shot setup doesn't- # enable tables the credentials can only ever 403 on. Transient failure falls back to- # "available", which is the pre-probe behavior.- try:- setup_permissions = source.get_endpoint_permissions(- source_config, self.team_id, [schema.name for schema in source_schemas]- )- except Exception as e:- capture_exception(e, {"source_type": source_type, "team_id": self.team_id})- setup_permissions = {}-- # Some sources report a probe that couldn't run as a per-table reason rather than raising- # (Stripe does this so the picker can render one row per failure). Setup has no such UI: a- # blanket denial would silently create a source with every table off. Credentials that- # genuinely read nothing are already rejected by validate_credentials above, so read- # "everything denied" as an unreliable probe and keep the polling defaults.- if setup_permissions and all(setup_permissions.get(schema.name) for schema in source_schemas):- setup_permissions = {}-- # Build the schemas array server-side so the caller never has to. We've already validated- # config + credentials above, so `_create_external_data_source` skips that second gate- # (`skip_credential_validation`) to avoid a duplicate live credential round-trip.- payload["schemas"] = build_default_schemas(source_schemas, permission_errors=setup_permissions)-- response = self._create_external_data_source(- request,- source_type=source_type,- payload=payload,- prefix=serializer.validated_data.get("prefix"),- description=serializer.validated_data.get("description"),- access_method=ExternalDataSource.AccessMethod.WAREHOUSE,- created_via=ExternalDataSource.CreatedVia.MCP,- direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),- skip_credential_validation=True,- )- # Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.- if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:- resolved.credential.delete()-- if response.status_code == status.HTTP_201_CREATED and isinstance(source, WebhookSource):- webhook_result = self._auto_register_webhook(- source, source_config, str(response.data["id"]), source_schemas, permission_errors=setup_permissions- )- if webhook_result is not None:- response.data["webhook"] = webhook_result- return response-- @extend_schema(request=SourcePreviewRequestSerializer, responses={200: SourcePreviewResponseSerializer})- @action(methods=["POST"], detail=False)- def preview_resource(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Read a bounded sample of rows for one resource of a Custom REST source.-- Lets a manifest author verify `data_selector`, `primary_key`, and the incremental- `cursor_path` against live data before creating the source. Only `source_type: "Custom"`- is supported — other source types return 400. The read is bounded (single page per- resource, capped row count, short timeouts, no redirects). Manifest, validation, and SSRF- problems return 400; a live fetch failure returns 200 with `error` set and empty `rows`.- """- serializer = SourcePreviewRequestSerializer(data=request.data)- serializer.is_valid(raise_exception=True)-- source_type = serializer.validated_data["source_type"]- source = SourceRegistry.get_source(ExternalDataSourceType(source_type))- if not isinstance(source, CustomSource):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Preview is not supported for source type '{source_type}'."},- )-- payload = dict(serializer.validated_data.get("payload") or {})- is_valid, errors = source.validate_config(payload)- if not is_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid source config: {', '.join(errors)}"},- )- source_config = source.parse_config(payload)-- try:- # preview_resource runs its own SSRF host check and bounded live read, so no- # separate validate_credentials probe — the read is the credential check.- result = source.preview_resource(- cast(CustomSourceConfig, source_config),- self.team_id,- serializer.validated_data["resource_name"],- serializer.validated_data["limit"],- owner_user_id=self.request.user.id,- )- except ValueError as e:- # ManifestValidationError (a ValueError) for manifest/graph/URL issues, or a plain- # ValueError for an unknown resource_name / dependency cycle — all caller mistakes.- return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})-- return Response(- status=status.HTTP_200_OK,- data={- "rows": result.rows,- "row_count": result.row_count,- "columns": result.columns,- "error": result.error,- },- )-- @extend_schema(- request=DraftCustomManifestRequestSerializer,- responses={200: DraftCustomManifestResponseSerializer},- )- @action(methods=["POST"], detail=False)- def draft_custom_manifest(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Draft a Custom REST source manifest from API documentation using an LLM.-- Reads the docs (a URL fetched server-side, or pasted text / OpenAPI spec), asks the model to- author a RESTAPIConfig manifest, and validates it against the create-path checks — repairing- against validation errors up to a small budget. Returns the manifest for the user to review- and tweak in the builder before creating the source; it does NOT create anything. Gated by the- `dwh-custom-source-ai-builder` flag, and requires the org to have approved AI data processing,- since the docs are sent to the LLM gateway.- """- # Gate on access (flag) then consent before validating input shape, so a caller without the- # rollout or AI-data-processing opt-in is turned away before learning the request schema.- if not is_custom_source_ai_builder_enabled_for_team(self.team):- return Response(- status=status.HTTP_404_NOT_FOUND,- data={"message": "AI manifest drafting is not enabled for this organization."},- )-- if self.team.organization.is_ai_data_processing_approved is not True:- return Response(- status=status.HTTP_403_FORBIDDEN,- data={"message": "Enable AI data processing for this organization to use AI manifest drafting."},- )-- serializer = DraftCustomManifestRequestSerializer(data=request.data)- serializer.is_valid(raise_exception=True)- data = serializer.validated_data-- docs_text = (data.get("docs_text") or "").strip()- docs_source = "pasted_text" if docs_text else "fetched_url"- if not docs_text:- try:- docs_text = fetch_docs_text(data["docs_url"])- except DocsFetchError as e:- return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})-- try:- result = draft_manifest_sync(- team_id=self.team_id,- source_name=data.get("source_name") or "",- docs_text=docs_text,- )- except APIConnectionError as e:- capture_exception(e, {"team_id": self.team_id})- return Response(- status=status.HTTP_503_SERVICE_UNAVAILABLE,- data={- "message": "Couldn't reach the AI service. If you're running locally, the LLM gateway isn't running — author the manifest manually instead."- },- )- except Exception as e:- capture_exception(e, {"team_id": self.team_id})- return Response(- status=status.HTTP_502_BAD_GATEWAY,- data={"message": "The manifest drafting service failed. Try again, or author the manifest manually."},- )-- # Success-path telemetry: this is a paid, unbilled-to-customer Opus path, so capture how it- # performed (status, repair rounds, tables, where the docs came from) to drive a funnel from- # draft → source created. No docs content or credentials — none are accepted here anymore.- report_user_action(- cast(User, request.user),- "data warehouse custom source manifest drafted",- {- "draft_status": result.status,- "attempts": result.attempts,- "table_count": len(result.resource_names),- "docs_source": docs_source,- },- team=self.team,- request=request,- )-- return Response(- status=status.HTTP_200_OK,- data={- "draft_status": result.status,- "manifest_json": result.manifest_json,- "resource_names": result.resource_names,- "attempts": result.attempts,- "error": result.error,- },- )-- def _auto_register_webhook(- self,- source: WebhookSource,- source_config: Config,- source_id: str,- source_schemas: list[SourceSchema],- permission_errors: Mapping[str, str | None] | None = None,- ) -> dict | None:- """Best-effort webhook auto-registration for one-shot setup.-- The source was just created with polling sync defaults (webhook-only tables disabled). If the- source supports webhook auto-creation and the credentials allow it, register the webhook and- switch every webhook-capable table to the webhook sync method — unlocking webhook-only tables.- Failure never breaks setup: the polling defaults stay in place and webhook-only tables remain- disabled, exactly as if the source didn't support webhooks.- """- # Tables marked `should_sync_default=False` need explicit opt-in even when webhook-capable —- # one-shot setup must not force-enable what the schema picker would leave off (the same- # contract `build_default_schemas` honors). A table the credentials can't read is excluded- # for the same reason: a webhook can't deliver rows the connection was denied.- denied = {name for name, reason in (permission_errors or {}).items() if reason}- webhook_capable = {- s.name for s in source_schemas if s.supports_webhooks and s.should_sync_default and s.name not in denied- }- if not webhook_capable or source.webhook_template is None:- return None-- instance = ExternalDataSource.objects.get(pk=source_id, team_id=self.team_id)- # Registration can't succeed on a connection whose grants exclude webhook management, and- # one-shot setup has no manual-fallback UI to fall back into: leave the polling defaults.- blocked_reason = self._webhook_creation_blocked_reason(source, instance)- if blocked_reason is not None:- return {"success": False, "webhook_url": None, "error": blocked_reason, "pending_inputs": []}-- eligible_schemas = list(- ExternalDataSchema.objects.filter(source=instance, team_id=self.team_id, name__in=webhook_capable).exclude(- deleted=True- )- )- if not eligible_schemas:- return None-- def failure(error: str | None) -> dict:- return {"success": False, "webhook_url": None, "error": error, "pending_inputs": []}-- try:- hog_fn_result = get_or_create_webhook_hog_function(- team=self.team,- source=source,- source_id=str(instance.pk),- eligible_schemas=eligible_schemas,- config=source_config,- )- if hog_fn_result.error or hog_fn_result.hog_function_id is None:- return failure(hog_fn_result.error)-- registration = create_and_register_webhook(- source,- source_config,- hog_fn_result,- self.team_id,- api_version=source.resolve_api_version(instance.api_version),- )- except Exception as e:- capture_exception(e, {"source_id": source_id, "team_id": self.team_id})- return failure(str(e))-- if not registration.success:- # The external registration failed (e.g. credentials can't create webhooks), so the- # handler would never receive events — remove it and keep the polling defaults.- hog_function = HogFunction.objects.get(id=hog_fn_result.hog_function_id, team_id=self.team_id)- hog_function.deleted = True- hog_function.enabled = False- hog_function.save(update_fields=["deleted", "enabled"])- return failure(registration.error)-- for schema in eligible_schemas:- newly_enabled = not schema.should_sync- schema.sync_type = ExternalDataSchema.SyncType.WEBHOOK- schema.should_sync = True- schema.save(update_fields=["sync_type", "should_sync"])- if newly_enabled:- # Webhook-only tables were created disabled, so no sync schedule exists yet. The- # schedule still matters for webhook schemas: it ingests the buffered webhook events.- try:- sync_external_data_job_workflow(schema, create=True)- except Exception as e:- logger.exception(- "Could not create sync schedule for webhook schema", exc_info=e, schema_id=str(schema.id)- )-- return {- "success": True,- "webhook_url": registration.webhook_url,- "error": None,- "pending_inputs": list(registration.pending_inputs),- }-- def _validate_source_config_and_credentials(- self,- source: AnySource,- source_type_model: ExternalDataSourceType,- payload: dict,- access_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,- ) -> tuple[Response | None, Config | None]:- """Run the config + live credential gate (including the SSRF host check) for a source payload."""- if isinstance(source, CustomSource):- # The OAuth2 integration row pointer is server-managed: validation derives it by adopting- # the submitted auth_oauth2_* secrets into a row. Never trust a client-supplied pointer on- # a pre-create seam — it could reference a row the caller shouldn't consume.- payload.pop("auth_oauth2_integration_id", None)- is_valid, errors = source.validate_config(payload)- if not is_valid:- return (- Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid source config: {', '.join(errors)}"},- ),- None,- )- source_config: Config = source.parse_config(payload)-- try:- if isinstance(source, (PostgresSource, MySQLSource)):- credentials_valid, credentials_error = source.validate_credentials_for_access_method(- cast(Any, source_config),- self.team_id,- access_method,- require_ssl=new_source_requires_ssl(source_config),- )- elif isinstance(source, CustomSource):- # Create-time validation for an integration-backed manifest may only use an unbound integration- # owned by the requester, so the probe can't send another source's token to the submitted host.- credentials_valid, credentials_error = source.validate_credentials(- source_config, self.team_id, owner_user_id=self.request.user.id- )- else:- credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)- except Exception as e:- credentials_valid, credentials_error = _credentials_validation_failed(source, self.team_id, e)- if not credentials_valid:- return (- Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": credentials_error or INVALID_CREDENTIALS_FALLBACK_MESSAGE},- ),- None,- )- return None, source_config-- @extend_schema(request=SourceCredentialCreateSerializer, responses={201: SourceCredentialSerializer})- @action(methods=["POST"], detail=False)- def store_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Validate and store credentials for a data warehouse source without creating the source.-- Backs the source connect page: the user enters credentials directly in PostHog, they are- checked against a live connection, then stashed encrypted in a temporary store. The returned- credential id can be passed to `setup` as {'credential_id': <id>} to create the source — so- secrets never travel through an agent conversation. The stash is single-use: it is deleted- as soon as `setup` consumes it, and expires after 24 hours if never consumed.- """- serializer = SourceCredentialCreateSerializer(data=request.data)- serializer.is_valid(raise_exception=True)-- source_type = serializer.validated_data["source_type"]- payload = dict(serializer.validated_data["payload"])-- for key, value in payload.items():- if isinstance(value, str):- payload[key] = value.strip()-- source_type_model = ExternalDataSourceType(source_type)- source = SourceRegistry.get_source(source_type_model)-- error_response, _ = self._validate_source_config_and_credentials(source, source_type_model, payload)- if error_response is not None:- return error_response-- # Opportunistically purge expired stashes — there is no separate cleanup job.- PendingSourceCredential.objects.for_team(self.team_id).filter(expires_at__lte=timezone.now()).delete()-- credential = PendingSourceCredential.objects.create(- team_id=self.team_id,- source_type=source_type,- payload=payload,- created_by=cast(User, request.user),- )-- return Response(- status=status.HTTP_201_CREATED,- data=SourceCredentialSerializer(- {- "credential_id": credential.id,- "source_type": source_type,- "created_at": credential.created_at,- "expires_at": credential.expires_at,- }- ).data,- )-- @extend_schema(- parameters=[- OpenApiParameter(- name="source_type",- type=str,- location=OpenApiParameter.QUERY,- required=False,- description="Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').",- )- ],- responses=SourceCredentialSerializer(many=True),- )- @action(methods=["GET"], detail=False, pagination_class=None)- def stored_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """List credentials the requesting user stored via the source connect page that haven't been consumed yet.-- Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored- credentials are scoped to their creator: only the user who filled the connect page can list- or consume them. They are temporary too: they disappear once consumed by `setup` or when- they expire. Newest first, so after a user confirms they've finished the connect page, the- first entry for the source type is the one to pass to `setup`.- """- queryset = (- PendingSourceCredential.objects.for_team(self.team_id)- .filter(created_by=cast(User, request.user), expires_at__gt=timezone.now())- .order_by("-created_at")- )- source_type = request.query_params.get("source_type")- if source_type:- queryset = queryset.filter(source_type=source_type)-- data = [- {- "credential_id": credential.id,- "source_type": credential.source_type,- "created_at": credential.created_at,- "expires_at": credential.expires_at,- }- for credential in queryset- ]- return Response(status=status.HTTP_200_OK, data=SourceCredentialSerializer(data, many=True).data)-- @extend_schema(- request=None,- responses={- 200: OpenApiResponse(- response={- "type": "object",- "properties": {- "valid": {"type": "boolean"},- "errors": {"type": "array", "items": {"type": "string"}},- },- },- description="Whether the Postgres database satisfies CDC prerequisites.",- ),- 400: OpenApiResponse(description="Invalid config, disallowed host, or connection failure."),- },- )- @action(methods=["POST"], detail=False)- def check_cdc_prerequisites(self, request: Request, *arg: Any, **kwargs: Any):- """Validate CDC prerequisites against a live Postgres connection.-- Used by the source wizard to surface ✅/❌ checks before source creation,- and by the self-managed setup popup to verify user-created publications.- """- source_type = request.data.get("source_type")- if not isinstance(source_type, str) or not source_type_supports_cdc(source_type):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "CDC prerequisite checks are only supported for CDC enabled sources."},- )-- # Dispatch to the actual source class so subclasses (Supabase, Neon) can run- # their own pre-connection checks, e.g. rejecting pooled hosts for CDC.- source_impl = SourceRegistry.get_source(ExternalDataSourceType(source_type))- if not isinstance(source_impl, PostgresSource):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"CDC prerequisite checks are not supported for source type: {source_type}"},- )- is_valid, errors = source_impl.validate_config(request.data)- if not is_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid source config: {', '.join(errors)}"},- )- config = source_impl.parse_config(request.data)-- # SSRF protection: reject internal/private hosts (same as validate_credentials).- is_ssh_valid, ssh_errors = source_impl.ssh_tunnel_is_valid(config, self.team_id)- if not is_ssh_valid:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": ssh_errors or "SSH tunnel host not allowed"},- )- valid_host, host_errors = source_impl.is_database_host_valid(- config.host,- self.team_id,- using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False,- )- if not valid_host:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": host_errors or "Host not allowed"},- )-- management_mode = request.data.get("cdc_management_mode", "posthog")- if management_mode not in ("posthog", "self_managed"):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},- )-- tables = request.data.get("tables") or []- slot_name = request.data.get("cdc_slot_name") or None- publication_name = request.data.get("cdc_publication_name") or None-- try:- prereq_errors = source_impl.check_cdc_prerequisites(- config,- management_mode=management_mode,- tables=tables,- slot_name=slot_name,- publication_name=publication_name,- team_id=self.team_id,- )- except _EXPECTED_CONNECTION_ERRORS as e:- # Probing a user-supplied database to validate it is expected to fail when the host,- # credentials, or SSH tunnel are wrong or the server drops the connection. Surface it- # to the wizard as a 400, but don't capture it — these are user/upstream connection- # problems, not bugs in our code, and capturing every one floods error tracking.- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to Postgres to check prerequisites: {e}"},- )- except Exception as e:- capture_exception(e, {"source_type": source_type, "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to Postgres to check prerequisites: {e}"},- )-- return Response(- status=status.HTTP_200_OK,- data={"valid": len(prereq_errors) == 0, "errors": prereq_errors},- )-- def _get_cdc_adapter_or_400(self, instance: ExternalDataSource) -> tuple[CDCSourceAdapter | None, Response | None]:- """Look up the engine adapter for an existing source. Returns 400 if the- source's type doesn't support CDC."""- try:- return get_cdc_adapter(instance), None- except ValueError:- return None, Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"CDC is not supported for source type: {instance.source_type}"},- )-- @action(methods=["POST"], detail=True)- def check_cdc_prerequisites_for_source(self, request: Request, *arg: Any, **kwargs: Any):- """Validate CDC prerequisites for an existing source using its stored credentials.-- The detail=False ``check_cdc_prerequisites`` action is for the creation wizard,- where the client still holds the raw connection config (incl. password) in the- form. On the Configuration page the source already exists and secret fields are- stripped from API responses — so the client can't supply them. This reads the- stored (encrypted) credentials from the DB via the adapter instead.-- Body params: ``cdc_management_mode`` (``"posthog"`` | ``"self_managed"``),- ``cdc_slot_name`` (optional), ``cdc_publication_name`` (optional).- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None # narrowed by _get_cdc_adapter_or_400-- management_mode = request.data.get("cdc_management_mode", "posthog")- if management_mode not in ("posthog", "self_managed"):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},- )-- schema_hint = (instance.job_inputs or {}).get("schema") or "public"- try:- prereq_errors = adapter.validate_prerequisites(- instance,- management_mode=management_mode,- tables=[],- schema=schema_hint,- slot_name=request.data.get("cdc_slot_name") or None,- publication_name=request.data.get("cdc_publication_name") or None,- )- except _EXPECTED_CONNECTION_ERRORS as e:- # Probing the source's database to validate it is expected to fail when the host,- # credentials, or SSH tunnel are wrong, the server requires/refuses SSL, or it drops the- # connection. Surface it as a 400, but don't capture it — these are user/upstream- # connection problems, not bugs in our code, and capturing every one floods error- # tracking. Mirrors the detail=False check_cdc_prerequisites handler.- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to check prerequisites: {e}"},- )- except Exception as e:- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to check prerequisites: {e}"},- )-- return Response(- status=status.HTTP_200_OK,- data={"valid": len(prereq_errors) == 0, "errors": prereq_errors},- )-- @action(methods=["POST"], detail=True)- def enable_cdc(self, request: Request, *arg: Any, **kwargs: Any):- """Enable CDC on an existing source.-- Provisions engine-side CDC resources via the source's adapter, writes the CDC- config into ``source.job_inputs``, and ensures the CDC extraction schedule- exists. Re-runs prereq checks server-side so we never trust a stale- client-side check.-- Body params: ``cdc_management_mode`` (``"posthog"`` | ``"self_managed"``),- plus engine-specific identifier hints (e.g. ``cdc_slot_name``,- ``cdc_publication_name`` for Postgres). Universal tuning fields:- ``cdc_auto_drop_slot`` (optional bool), ``cdc_lag_warning_threshold_mb``- (optional int), ``cdc_lag_critical_threshold_mb`` (optional int).- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None # narrowed by _get_cdc_adapter_or_400-- if not is_cdc_enabled_for_team(self.team):- return Response(- status=status.HTTP_403_FORBIDDEN,- data={"message": "CDC is not enabled for this team."},- )-- existing = adapter.parse_cdc_config(instance)- if existing.enabled:- return Response(- status=status.HTTP_409_CONFLICT,- data={"message": "CDC is already enabled on this source."},- )-- management_mode = request.data.get("cdc_management_mode", "posthog")- if management_mode not in ("posthog", "self_managed"):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},- )-- # Validate prerequisites server-side — never trust a client-only check.- schema_hint = (instance.job_inputs or {}).get("schema") or "public"- try:- prereq_errors = adapter.validate_prerequisites(- instance,- management_mode=management_mode,- tables=[],- schema=schema_hint,- slot_name=request.data.get("cdc_slot_name") or None,- publication_name=request.data.get("cdc_publication_name") or None,- )- except _EXPECTED_CONNECTION_ERRORS as e:- # Expected user/upstream connection failure (bad host/credentials/SSH tunnel, server- # requires/refuses SSL, dropped connection). Surface as a 400 without capturing — see the- # check_cdc_prerequisites_for_source handler above.- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to check prerequisites: {e}"},- )- except Exception as e:- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to check prerequisites: {e}"},- )-- if prereq_errors:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "CDC prerequisites not met.", "errors": prereq_errors},- )-- cdc_error = self._setup_cdc_resources(adapter, instance, request.data)- if cdc_error is not None:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": cdc_error},- )-- # Ensure the global cleanup schedule exists. There are no CDC schemas yet (the user- # picks sync_type=cdc per schema afterward), so `sync_cdc_extraction_schedule` is a- # no-op here — the extraction schedule is authoritatively (re)created when a schema is- # switched to CDC. A failure here therefore can't leave a "CDC on, never runs" state:- # the slot + config are valid and the schedule self-heals on the first CDC schema- # toggle. Surface failures (capture, not just log) and flag them in the response.- schedules_ok = True- try:- sync_cdc_extraction_schedule(instance, create=True)- ensure_cdc_slot_cleanup_schedule()- except Exception as e:- schedules_ok = False- logger.exception("Could not create CDC schedules after enable_cdc", exc_info=e)- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})-- return Response(status=status.HTTP_200_OK, data={"success": True, "schedules_ready": schedules_ok})-- @action(methods=["POST"], detail=True)- def disable_cdc(self, request: Request, *arg: Any, **kwargs: Any):- """Disable CDC on an existing source.-- Cancels any running CDC extraction workflow, deletes the extraction schedule,- delegates engine-side teardown to the source's adapter (drops slot/publication- for Postgres; equivalent for other engines), clears ``cdc_*`` keys from- ``job_inputs``, soft-deletes companion CDC tables, and sets all CDC schemas to- ``sync_type=None``, ``should_sync=False`` so the user must pick a new sync- strategy before they resume.- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None-- cdc_config = adapter.parse_cdc_config(instance)- if not cdc_config.enabled:- return Response(status=status.HTTP_200_OK, data={"success": True, "already_disabled": True})-- # Read the CDC schemas before the sync_type reset below, while they're still- # marked CDC. Scoped so we don't touch unrelated incremental/full-refresh syncs.- cdc_schemas = list(- ExternalDataSchema.objects.filter(- source=instance,- sync_type=ExternalDataSchema.SyncType.CDC,- )- .exclude(deleted=True)- .select_related("table")- )- # Disabling cancels jobs, drops the slot, purges buffered change data, and resets- # every CDC schema — editor on the source isn't enough when a table is locked below it.- self._assert_can_write_schemas(cdc_schemas)- cdc_schema_ids = [schema.id for schema in cdc_schemas]- running_jobs = ExternalDataJob.objects.filter(- pipeline_id=instance.pk,- team_id=instance.team_id,- status="Running",- schema_id__in=cdc_schema_ids,- ).exclude(workflow_id__isnull=True)- for running_job in running_jobs:- if not running_job.workflow_id:- continue- try:- cancel_external_data_workflow(running_job.workflow_id)- except Exception as e:- capture_exception(e, {"source_id": str(instance.id), "workflow_id": running_job.workflow_id})-- # Generic schedule teardown: schedule lives on our side, independent of engine.- try:- delete_cdc_extraction_schedule(str(instance.id))- except Exception:- logger.exception("Failed to delete CDC extraction schedule", extra={"source_id": str(instance.id)})-- # Engine-side teardown: best-effort, never blocks the disable.- try:- adapter.cleanup_resources(instance)- except Exception as e:- logger.exception("Failed engine-side CDC cleanup during disable_cdc", exc_info=e)- capture_exception(e, {"source_id": str(instance.id)})-- # Drop each schema's S3 change buffer: the shadow lane's files are raw customer- # change data with no consumer once CDC is off, and nothing else expires them.- for schema_id in cdc_schema_ids:- purge_buffer_prefix(instance.team_id, str(schema_id), logger)-- with transaction.atomic():- # Clear any broken marker (recovery contract): leaving a stale cdc_broken in- # sync_type_config would make CDC look broken the moment it's re-enabled.- # Must be inside the atomic block so a failed schema-state reset rolls this back too.- for schema_id in cdc_schema_ids:- try:- update_sync_type_config_keys(- schema_id, instance.team_id, removes=["cdc_broken", "cdc_extraction_paused"]- )- except ExternalDataSchema.DoesNotExist:- pass-- # Force CDC schemas to pick a new strategy by clearing sync_type and pausing.- ExternalDataSchema.objects.filter(- source=instance,- sync_type=ExternalDataSchema.SyncType.CDC,- ).exclude(deleted=True).update(sync_type=None, should_sync=False)-- # Soft-delete `_cdc` companion DataWarehouseTable rows so the next sync- # rebuilds them once the user picks a new strategy.- DataWarehouseTable.objects.filter(- external_data_source_id=instance.id,- team_id=self.team_id,- deleted=False,- name__endswith="_cdc",- ).update(deleted=True)-- # Clear ALL cdc_* keys from job_inputs — leaving stale engine identifiers- # behind (e.g. `cdc_consistent_point`) would corrupt resume tracking if- # CDC is later re-enabled.- job_inputs = dict(instance.job_inputs or {})- for key in list(job_inputs.keys()):- if key.startswith("cdc_"):- job_inputs.pop(key, None)- instance.job_inputs = job_inputs- instance.save(update_fields=["job_inputs", "updated_at"])-- return Response(status=status.HTTP_200_OK, data={"success": True})-- @extend_schema(- request=None,- responses={- 200: OpenApiResponse(- response={- "type": "object",- "properties": {- "success": {"type": "boolean"},- "schemas_reset": {"type": "integer"},- },- },- description="CDC repaired; schemas_reset CDC schemas will fully re-sync.",- ),- 400: OpenApiResponse(- description="CDC not enabled, no active CDC schemas, source looks healthy, or engine-side recreation failed."- ),- 409: OpenApiResponse(description="A repair is already running for this source."),- },- )- @action(methods=["POST"], detail=True)- def repair_cdc(self, request: Request, *arg: Any, **kwargs: Any):- """Repair CDC on a source whose replication resources were lost.-- Only proceeds on evidence of breakage (a persisted broken marker, or a live probe- showing the slot/publication missing) — repairing a healthy source would drop its- slot and force a full re-sync. Cancels running CDC jobs, recreates the engine-side- slot/publication against the stored CDC config, resets every active CDC schema to- snapshot mode for a full re-sync (changes since the old slot died are- unrecoverable), clears the broken markers, and resumes the paused schedules.- Idempotent: safe to retry after a partial failure. Concurrent repairs of the same- source are rejected with a 409.- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None # narrowed by _get_cdc_adapter_or_400-- cdc_config = adapter.parse_cdc_config(instance)- if not cdc_config.enabled:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "CDC is not enabled on this source."},- )-- try:- schemas_reset = repair_cdc_source(instance)- except CDCRepairInProgress as e:- return Response(status=status.HTTP_409_CONFLICT, data={"message": str(e)})- except CDCRepairError as e:- return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})- except _EXPECTED_CONNECTION_ERRORS as e:- # Expected user/upstream connection failure — surface as a 400 without capturing,- # mirroring the enable_cdc handler.- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to repair CDC: {e}"},- )- except Exception as e:- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not repair CDC: {e}"},- )-- return Response(status=status.HTTP_200_OK, data={"success": True, "schemas_reset": schemas_reset})-- @extend_schema(- request=None,- responses={- 200: OpenApiResponse(- response={"type": "object", "properties": {"success": {"type": "boolean"}}},- description="CDC resumed; the extraction schedule is unpaused.",- ),- 400: OpenApiResponse(- description="CDC not enabled, the slot/publication were lost (use Repair CDC), the source is still "- "unreachable, or unpausing failed."- ),- },- )- @action(methods=["POST"], detail=True)- def resume_cdc(self, request: Request, *arg: Any, **kwargs: Any):- """Resume a CDC source whose extraction schedule was paused by a non-retryable- failure that left the replication slot intact (bad credentials, SSL/host errors).-- Once the user has fixed the root cause, this re-probes the source DB — confirming- the connection now succeeds and the slot/publication still exist — then unpauses the- extraction schedule so streaming resumes from where it left off. No re-snapshot, so- it's the cheap counterpart to Repair CDC. If the slot/publication are actually gone- (``cdc_broken``, or a live probe showing them missing), resume is refused — only- Repair CDC can recreate them, at the cost of a full re-sync.- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None # narrowed by _get_cdc_adapter_or_400-- cdc_config = adapter.parse_cdc_config(instance)- if not cdc_config.enabled:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "CDC is not enabled on this source."},- )-- cdc_schemas = list(- ExternalDataSchema.objects.filter(- source=instance,- sync_type=ExternalDataSchema.SyncType.CDC,- should_sync=True,- ).exclude(deleted=True)- )- if not cdc_schemas:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "No schemas are syncing via change data capture, so there is nothing to resume."},- )-- # A broken source has lost its slot/publication — resuming would just re-fail on the- # next tick. Route the user to Repair CDC, which recreates them (and re-syncs).- if any((schema.sync_type_config or {}).get("cdc_broken") for schema in cdc_schemas):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "The replication slot or publication was lost. Use Repair CDC to recreate it."},- )-- # Re-probe the source: this both re-validates the connection (a still-wrong password- # raises here) and confirms the slot/publication survive, so we never unpause straight- # back into the same deterministic failure.- try:- live_status = adapter.get_status(instance)- except _EXPECTED_CONNECTION_ERRORS as e:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Could not connect to source to resume CDC — check the credentials and try again: {e}"- },- )- except Exception as e:- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to resume CDC: {e}"},- )-- if live_status.get("slot_exists") is False or live_status.get("publication_exists") is False:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "The replication slot or publication is missing. Use Repair CDC to recreate it."},- )-- try:- # Recreate the schedule if it was deleted out-of-band — unpausing a missing schedule is a- # silent no-op that would report success while CDC never runs (same ordering as CDC repair's- # _resume_schedules). sync builds an unpaused schedule; the explicit unpause covers the- # already-existing-but-paused case.- sync_cdc_extraction_schedule(instance)- unpause_cdc_extraction_schedule(str(instance.id))- except Exception as e:- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not resume CDC: {e}"},- )-- # Extraction is running again: clear the paused marker so the schema stops reading as- # halted (failure digest badge, loader status guard). Status stays FAILED until a run- # actually succeeds. After the unpause, so a failure here leaves the marker for retry.- for schema in cdc_schemas:- try:- update_sync_type_config_keys(schema.id, instance.team_id, removes=["cdc_extraction_paused"])- except ExternalDataSchema.DoesNotExist:- pass-- return Response(status=status.HTTP_200_OK, data={"success": True})-- @action(methods=["POST"], detail=True)- def update_cdc_settings(self, request: Request, *arg: Any, **kwargs: Any):- """Update CDC tuning fields without enabling/disabling.-- Lets users edit ``cdc_auto_drop_slot``, ``cdc_lag_warning_threshold_mb``, and- ``cdc_lag_critical_threshold_mb`` independently. These fields are universal- across engines. Engine-specific identifiers (slot name, management mode, …)- are immutable post-enable — switching them requires disable + enable.- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None-- cdc_config = adapter.parse_cdc_config(instance)- if not cdc_config.enabled:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "CDC is not enabled on this source."},- )-- job_inputs = dict(instance.job_inputs or {})- updates: dict[str, Any] = {}-- if "cdc_auto_drop_slot" in request.data:- updates["cdc_auto_drop_slot"] = bool(request.data["cdc_auto_drop_slot"])-- for field in ("cdc_lag_warning_threshold_mb", "cdc_lag_critical_threshold_mb"):- if field in request.data:- try:- value = int(request.data[field])- except (TypeError, ValueError):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"{field} must be an integer."},- )- if value < 1:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"{field} must be >= 1."},- )- updates[field] = value-- warn = updates.get("cdc_lag_warning_threshold_mb", job_inputs.get("cdc_lag_warning_threshold_mb"))- crit = updates.get("cdc_lag_critical_threshold_mb", job_inputs.get("cdc_lag_critical_threshold_mb"))- if warn is not None and crit is not None and int(warn) >= int(crit):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Warning threshold must be less than critical threshold."},- )-- if not updates:- return Response(status=status.HTTP_200_OK, data={"success": True, "unchanged": True})-- job_inputs.update(updates)- instance.job_inputs = job_inputs- instance.save(update_fields=["job_inputs", "updated_at"])-- return Response(status=status.HTTP_200_OK, data={"success": True})-- @action(methods=["GET"], detail=True)- def cdc_status(self, request: Request, *arg: Any, **kwargs: Any):- """Live CDC health for an existing source: slot/publication existence and WAL lag.-- Reads from the source DB via the engine adapter. Returns ``{"enabled": false}``- when CDC is off, or the stored config plus live ``slot_exists`` /- ``publication_exists`` / ``lag_bytes`` when on. 400s if the source DB is- unreachable so the UI can show a degraded/unreachable state.- """- instance: ExternalDataSource = self.get_object()-- adapter, err = self._get_cdc_adapter_or_400(instance)- if err is not None:- return err- assert adapter is not None-- cdc_config = adapter.parse_cdc_config(instance)- if not cdc_config.enabled:- return Response(status=status.HTTP_200_OK, data={"enabled": False})-- try:- live_status = adapter.get_status(instance)- except Exception as e:- # An unreachable source DB is the degraded state this endpoint exists to report, so- # don't capture expected connection failures as error-tracking noise. Capture only- # unexpected errors, which point at a bug in our status read.- if not adapter.is_connection_error(e):- capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Could not connect to source to read CDC status: {e}"},- )-- # Paused-but-slot-intact means a non-retryable failure stopped the schedule; the UI offers- # Resume (vs Repair) so the user can restart without a full re-sync. Best-effort: a Temporal- # hiccup must not 500 this otherwise DB-only status read, so degrade to not-paused.- try:- schedule_paused = is_cdc_extraction_schedule_paused(str(instance.id))- except Exception:- logger.warning("cdc_status_schedule_paused_lookup_failed", source_id=str(instance.id), exc_info=True)- schedule_paused = False-- return Response(- status=status.HTTP_200_OK,- data={- "enabled": True,- "management_mode": cdc_config.management_mode,- "slot_name": cdc_config.slot_name,- "publication_name": cdc_config.publication_name,- "lag_warning_threshold_mb": cdc_config.lag_warning_threshold_mb,- "lag_critical_threshold_mb": cdc_config.lag_critical_threshold_mb,- "schedule_paused": schedule_paused,- **live_status,- },- )-- @action(methods=["POST"], detail=False)- def source_prefix(self, request: Request, *arg: Any, **kwargs: Any):- prefix = request.data.get("prefix", None)- source_type = request.data["source_type"]- access_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)-- if ExternalDataSource.is_system_managed_prefix(prefix):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": RESERVED_SOURCE_NAME_MESSAGE},- )-- if access_method == ExternalDataSource.AccessMethod.DIRECT:- if source_type not in direct_capable_source_types():- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},- )-- normalized_prefix = prefix.strip() if isinstance(prefix, str) else ""- if not normalized_prefix:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Name is required for direct query sources"},- )-- return Response(status=status.HTTP_200_OK)-- if not prefix:- if self.prefix_required(source_type):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": "You already have a source of this type. Add a table prefix so this connection's tables don't clash with your existing source."- },- )- elif self.prefix_exists(source_type, prefix):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Another source of this type already uses the prefix '{prefix}'. Choose a different prefix so this connection's tables don't clash."- },- )-- return Response(status=status.HTTP_200_OK)-- @action(methods=["GET"], detail=True, pagination_class=None)- @extend_schema(- parameters=[- OpenApiParameter(- name="after",- type=str,- location=OpenApiParameter.QUERY,- required=False,- description="ISO timestamp — only return jobs created after this date.",- ),- OpenApiParameter(- name="before",- type=str,- location=OpenApiParameter.QUERY,- required=False,- description="ISO timestamp — only return jobs created before this date.",- ),- OpenApiParameter(- name="schemas",- type={"type": "array", "items": {"type": "string"}},- location=OpenApiParameter.QUERY,- required=False,- description="Filter jobs by table schema names.",- ),- ],- responses=ExternalDataJobSerializers(many=True),- )- def jobs(self, request: Request, *arg: Any, **kwargs: Any):- instance: ExternalDataSource = self.get_object()- after = request.query_params.get("after", None)- before = request.query_params.get("before", None)- schemas = request.query_params.getlist("schemas")-- # select_related joins the full ExternalDataSchema row; defer its large JSON/text- # columns so the serializer only pulls the fields SimpleExternalDataSchemaSerializer- # actually reads (sync_type_config + latest_error can each be sizeable).- # Non-billable jobs are included on purpose: the UI shows them tagged so a sync the- # customer wasn't charged for is still visible in the history.- jobs = (- instance.jobs.select_related("schema")- .defer("schema__sync_type_config", "schema__latest_error")- .order_by("-created_at")- )-- if schemas:- jobs = jobs.filter(schema__name__in=schemas)- if after:- after_date = parser.parse(after)- jobs = jobs.filter(created_at__gt=after_date)- if before:- before_date = parser.parse(before)- jobs = jobs.filter(created_at__lt=before_date)-- jobs = jobs[:50]-- return Response(- status=status.HTTP_200_OK,- data=ExternalDataJobSerializers(- jobs, many=True, read_only=True, context=self.get_serializer_context()- ).data,- )-- @extend_schema(- parameters=[- OpenApiParameter(- name="source_type",- type=str,- location=OpenApiParameter.QUERY,- required=False,- description=(- "Comma-separated source type(s) to return config for, e.g. 'Postgres' or "- "'Postgres,Stripe'. Strongly recommended: the unfiltered response describes every "- "supported source and is very large. Omit only to enumerate the available types."- ),- )- ],- responses={200: SourceConfigMapResponse},- )- @action(methods=["GET"], detail=False)- def wizard(self, request: Request, *arg: Any, **kwargs: Any):- # The documented-tables catalog is only consumed by the posthog.com docs build (via the- # public endpoint) — skipping it here cuts ~40% off an already >1 MB response.- configs = build_source_configs(include_tables=False)-- requested = request.query_params.get("source_type")- if requested:- requested_types = [t.strip() for t in requested.split(",") if t.strip()]- unknown = [t for t in requested_types if t not in configs]- if unknown:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Unknown source_type(s): {', '.join(sorted(unknown))}. "- "Omit source_type to list every available type."- },- )- configs = {st: config for st, config in configs.items() if st in requested_types}-- response = Response(status=status.HTTP_200_OK, data=configs)- # The catalog is deploy-static and identical for every user (no team/user input), so let the- # browser reuse it across navigations instead of re-downloading and re-parsing several hundred- # KB on each visit to the new-source page. `private` because the route is auth-gated; a new- # source ships at most once per deploy, so a short freshness window is safe.- patch_cache_control(response, private=True, max_age=600)- return response-- @extend_schema(- parameters=[- OpenApiParameter(- name="source_type",- type=str,- location=OpenApiParameter.QUERY,- required=True,- description="The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').",- )- ],- responses=SourceConnectLinkSerializer,- )- @action(methods=["GET"], detail=False)- def connect_link(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Return a secure browser link for connecting a data warehouse source.-- The link opens a minimal connect page rendering the source's full connection form — OAuth options- included — with no table selection and no source creation. The user authenticates in their browser,- secrets never pass through the agent, and the agent finishes setup afterwards by passing the stored- credential id to data-warehouse-source-setup.- """- source_type = request.query_params.get("source_type")- if not source_type:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Missing required parameter: source_type"},- )- try:- source_type_model = ExternalDataSourceType(source_type)- except ValueError:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Unknown source_type '{source_type}'"},- )-- source = SourceRegistry.get_source(source_type_model)- oauth_field = _find_top_level_oauth_field(source.get_source_config.model_dump())- action_phrase = (- f"connect their {source_type} account" if oauth_field else f"enter their {source_type} connection details"- )-- data = {- "source_type": source_type,- "auth_method": "oauth" if oauth_field else "credentials",- "connect_url": (- f"{settings.SITE_URL}/project/{self.team_id}/data-warehouse/connect?kind={quote(str(source_type))}"- ),- "instructions": (- f"Share this link with the user. They {action_phrase} directly in PostHog — never ask them to "- "paste credentials or tokens into the chat. The page only stores the connection details; it does "- "not create the source. Once the user confirms they're done, find the stored credential id via "- f"data-warehouse-stored-credentials-list (source_type='{source_type}', newest first) and call "- 'data-warehouse-source-setup with {"credential_id": <id>} in the payload. Stored credentials are '- "single-use, expire after 24 hours, and are only visible to and consumable by the PostHog user "- "who entered them — so the page must be filled by the same user this session authenticates as."- ),- }- return Response(status=status.HTTP_200_OK, data=SourceConnectLinkSerializer(data).data)-- @extend_schema(responses=ExternalDataSourceConnectionOptionSerializer(many=True))- @action(- methods=["GET"],- detail=False,- pagination_class=None,- filter_backends=[],- required_scopes=["external_data_source:read"],- )- def connections(self, request: Request, *args: Any, **kwargs: Any) -> Response:- connection_sources = (- ExternalDataSource._base_manager.filter(- team_id=self.team_id,- source_type__in=direct_capable_source_types(),- )- # Pure-direct sources are always live; synced sources only when the toggle is on.- .filter(Q(access_method=ExternalDataSource.AccessMethod.DIRECT) | Q(direct_query_enabled=True))- .exclude(deleted=True)- .only(- "id",- "prefix",- "description",- "connection_metadata",- "source_type",- "access_method",- )- .order_by(self.ordering)- )- managed_candidates = connection_sources.filter(ExternalDataSource.ready_managed_warehouse_q()).only(- "id",- "team_id",- "prefix",- "description",- "connection_metadata",- "source_type",- "access_method",- "direct_query_enabled",- "job_inputs",- )- managed_source = next(- (source for source in managed_candidates if source.is_dynamic_managed_warehouse),- None,- ) or next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)- if managed_source is not None:- external_sources = connection_sources.exclude(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)- else:- canonical_source = _canonical_legacy_managed_warehouse_source(connection_sources)- external_sources = _hide_noncanonical_managed_warehouse_sources(connection_sources, canonical_source)- if is_service_auth(request):- accessible_external_sources = external_sources- else:- accessible_external_sources = self.user_access_control.filter_queryset_by_access_level(external_sources)- if not self.user_access_control.has_resource_access(- "external_data_source"- ) and not self.user_access_control.has_any_specific_access_for_resource(- "external_data_source", required_level="viewer"- ):- accessible_external_sources = accessible_external_sources.filter(created_by=cast(User, request.user))- accessible_sources = list(accessible_external_sources)- options = ([managed_source] if managed_source is not None else []) + accessible_sources-- serializer = ExternalDataSourceConnectionOptionSerializer(- options,- many=True,- context={"builtin_managed_warehouse_source_id": managed_source.pk if managed_source is not None else None},- )- return Response(status=status.HTTP_200_OK, data=serializer.data)-- @extend_schema(responses=DirectConnectionSourceOptionSerializer(many=True))- @action(methods=["GET"], detail=False, pagination_class=None, filter_backends=[])- def direct_connection_options(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Source types the user can add as a direct connection, driven by the direct-SQL capability- surface so the picker never drifts from the engines we actually support."""- direct_types = direct_capable_source_types()- options = [- {- "source_type": source_type,- "label": config.get("label") or source_type,- "icon_path": config.get("iconPath"),- }- for source_type, config in build_source_configs(include_tables=False).items()- if source_type in direct_types- ]- options.sort(key=lambda option: str(option["label"]).lower())-- serializer = DirectConnectionSourceOptionSerializer(options, many=True)- return Response(status=status.HTTP_200_OK, data=serializer.data)-- @extend_schema(- request=DestinationLinkSerializer,- responses={200: SourceDestinationsSerializer},- )- @action(methods=["GET", "PATCH"], detail=True)- def destinations(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Read or replace the destinations every table on this source syncs to.-- A table with its own override ignores this set until the override is cleared.- """- source = self.get_object()-- if request.method == "GET":- attached = [- str(link.destination_id)- for link in ExternalDataSourceDestination.objects.for_team(self.team_id)- .filter(source_id=source.id, enabled=True)- .exclude(destination__deleted=True)- ]- # A source nobody configured has no links but is not syncing nowhere: it syncs to the- # PostHog warehouse. Report where it actually goes, or the picker shows every- # destination off and saving from that state silently drops the warehouse.- # Looked up rather than resolved, because `resolve_destinations` creates the- # warehouse row on demand and a GET must not write.- if not attached:- warehouse = (- ExternalDataDestination.objects.for_team(self.team_id)- .filter(type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE, deleted=False)- .first()- )- attached = [str(warehouse.id)] if warehouse else []- return Response(- status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).data- )-- serializer = DestinationLinkSerializer(data=request.data)- serializer.is_valid(raise_exception=True)-- # Editor on the source isn't enough on its own: this replaces the destination set every- # table without its own override inherits, and (like `destroy`) never resolves a schema- # through DRF's object permissions, so a table locked below the source would otherwise be- # rerouted to a destination its editor never had access to.- schemas = list(- ExternalDataSchema.objects.exclude(deleted=True)- .filter(team_id=self.team_id, source_id=source.id)- .select_related("table")- )- self._assert_can_write_schemas(schemas)-- attached = set_source_destinations(- team_id=self.team_id,- source_id=source.id,- destination_ids=serializer.validated_data["destination_ids"],- )- return Response(- status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).data- )-- @action(methods=["PATCH"], detail=True)- def revenue_analytics_config(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Update the revenue analytics configuration and return the full external data source."""- external_data_source = self.get_object()- config = external_data_source.revenue_analytics_config_safe-- config_serializer = ExternalDataSourceRevenueAnalyticsConfigSerializer(config, data=request.data, partial=True)- config_serializer.is_valid(raise_exception=True)- config_serializer.save()-- table_prefix = external_data_source.prefix or ""-- if config.enabled:- managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(- team=self.team,- kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,- )- managed_viewset.sync_views()- ensure_person_join(self.team.pk, table_prefix)- else:- try:- managed_viewset = DataWarehouseManagedViewSet.objects.get(- team=self.team,- kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,- )- managed_viewset.delete_with_views()-- except DataWarehouseManagedViewSet.DoesNotExist:- pass- remove_person_join(self.team.pk, table_prefix)-- # Return the full external data source with updated config- source_serializer = self.get_serializer(external_data_source, context=self.get_serializer_context())- return Response(source_serializer.data)-- def _compute_missing_webhook_events(- self,- source: WebhookSource,- config: Any,- instance: ExternalDataSource,- external_status: ExternalWebhookInfo | None,- ) -> list[str]:- """Desired events not yet on the provider webhook — surfaced so manual-webhook users- (or keys lacking webhook-write scope) know what to add."""- if not external_status or not external_status.exists or external_status.error:- return []-- eligible_schema_names = list(- ExternalDataSchema.objects.filter(- source=instance,- team_id=self.team_id,- sync_type=ExternalDataSchema.SyncType.WEBHOOK,- should_sync=True,- )- .exclude(deleted=True)- .values_list("name", flat=True)- )-- desired = source.get_desired_webhook_events(config, eligible_schema_names)- if not desired:- return []-- current = set(external_status.enabled_events or [])- if "*" in current:- return []-- return sorted(e for e in desired if e not in current)-- @action(methods=["GET"], detail=True)- def webhook_info(self, request: Request, *args: Any, **kwargs: Any) -> Response:- instance: ExternalDataSource = self.get_object()- source_type = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type)-- if not isinstance(source, WebhookSource):- return Response(- status=status.HTTP_200_OK,- data={- "supports_webhooks": False,- "exists": False,- "webhook_url": None,- "schema_mapping": {},- "external_status": None,- },- )-- blocked_reason = self._webhook_creation_blocked_reason(source, instance)-- hog_function = HogFunction.objects.filter(- team=self.team,- type="warehouse_source_webhook",- inputs__source_id__value=str(instance.pk),- deleted=False,- ).first()-- if not hog_function:- return Response(- status=status.HTTP_200_OK,- data={- "supports_webhooks": True,- "exists": False,- "auto_creation_blocked_reason": blocked_reason,- },- )-- webhook_url = get_webhook_url(hog_function.id)-- external_status: ExternalWebhookInfo | None = None- missing_events: list[str] = []-- if instance.job_inputs:- try:- config = source.parse_config(instance.job_inputs)- external_status = source.get_external_webhook_info(- config, webhook_url, self.team_id, api_version=source.resolve_api_version(instance.api_version)- )- missing_events = self._compute_missing_webhook_events(source, config, instance, external_status)- except Exception as e:- capture_exception(e)-- schema_mapping = {}- if hog_function.inputs:- schema_mapping = hog_function.inputs.get("schema_mapping", {}).get("value", {})-- webhook_field_names = {f.name for f in (source.get_source_config.webhookFields or [])}- all_inputs = HogFunctionSerializer(hog_function).data.get("inputs") or {}- webhook_inputs = {k: v for k, v in all_inputs.items() if k in webhook_field_names}-- return Response(- status=status.HTTP_200_OK,- data={- "supports_webhooks": True,- "exists": True,- "hog_function": {- "id": str(hog_function.id),- "name": hog_function.name,- "enabled": hog_function.enabled,- "created_at": hog_function.created_at.isoformat(),- "status": hog_function.status,- },- "webhook_url": webhook_url,- "schema_mapping": schema_mapping,- "inputs": webhook_inputs,- "external_status": dataclasses.asdict(external_status) if external_status else None,- "missing_events": missing_events,- "auto_creation_blocked_reason": blocked_reason,- },- )-- def _webhook_creation_blocked_reason(self, source: WebhookSource, instance: ExternalDataSource) -> str | None:- """Ask the source whether this connection can never create the provider-side webhook.- Best-effort: an unparseable config or a source-side failure leaves the button offered,- which is the behavior before the check existed."""- if not instance.job_inputs:- return None- try:- return source.webhook_creation_blocked_reason(source.parse_config(instance.job_inputs), self.team_id)- except Exception as e:- capture_exception(e)- return None-- @action(methods=["POST"], detail=True)- def create_webhook(self, request: Request, *args: Any, **kwargs: Any) -> Response:- instance: ExternalDataSource = self.get_object()-- if not instance.job_inputs:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Source has no configuration"},- )-- source_type = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type)-- if not isinstance(source, WebhookSource):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "This source type does not support webhooks"},- )-- # A connection known to lack the grant can't be fixed by trying. The hog function is still- # minted below so manual setup has a URL to paste; only the doomed provider round-trip (one- # call per repository, for GitHub) is skipped.- blocked_reason = self._webhook_creation_blocked_reason(source, instance)-- effective_api_version = source.resolve_api_version(instance.api_version)- try:- config = source.parse_config(instance.job_inputs)- source_schemas = source.get_schemas(config, self.team_id, api_version=effective_api_version)- except ValidationError as e:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Invalid source configuration", "details": getattr(e, "detail", str(e))},- )- except Exception as e:- capture_exception(e)- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Failed to load source configuration or schemas"},- )-- webhook_source_schemas = {s.name: s for s in source_schemas if s.supports_webhooks}-- db_schemas = ExternalDataSchema.objects.filter(- source=instance,- team_id=self.team_id,- sync_type=ExternalDataSchema.SyncType.WEBHOOK,- should_sync=True,- ).exclude(deleted=True)-- eligible_schemas = [s for s in db_schemas if s.name in webhook_source_schemas]-- hog_fn_result = get_or_create_webhook_hog_function(- team=self.team,- source=source,- source_id=str(instance.pk),- eligible_schemas=eligible_schemas,- config=config,- )-- if hog_fn_result.error:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": hog_fn_result.error},- )-- if blocked_reason is not None:- return Response(- status=status.HTTP_200_OK,- data={- "success": False,- "webhook_url": hog_fn_result.webhook_url,- "error": blocked_reason,- "pending_inputs": [],- },- )-- result = create_and_register_webhook(- source, config, hog_fn_result, self.team_id, api_version=effective_api_version- )-- return Response(- status=status.HTTP_200_OK,- data={- "success": result.success,- "webhook_url": result.webhook_url,- "error": result.error,- "pending_inputs": result.pending_inputs,- },- )-- @action(methods=["POST"], detail=True)- def update_webhook_inputs(self, request: Request, *args: Any, **kwargs: Any) -> Response:- instance: ExternalDataSource = self.get_object()-- if not instance.job_inputs:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Source has no configuration"},- )-- source_type = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type)-- if not isinstance(source, WebhookSource):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "This source type does not support webhooks"},- )-- inputs = request.data.get("inputs", {})- if not inputs or not isinstance(inputs, dict):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "No inputs provided"},- )-- source_config = source.get_source_config- webhook_fields = source_config.webhookFields or []- webhook_field_names = {f.name for f in webhook_fields}-- invalid_keys = set(inputs.keys()) - webhook_field_names- if invalid_keys:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Invalid input keys: {', '.join(invalid_keys)}"},- )-- required_fields = [f.name for f in webhook_fields if getattr(f, "required", False)]- blanked_required = [name for name in required_fields if name in inputs and not inputs[name]]- if blanked_required:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": f"Missing required fields: {', '.join(blanked_required)}"},- )-- try:- hog_function = HogFunction.objects.get(- team=self.team,- type="warehouse_source_webhook",- inputs__source_id__value=str(instance.pk),- deleted=False,- )- except HogFunction.DoesNotExist:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "No webhook function found for this source. Create a webhook first."},- )-- try:- config = source.parse_config(instance.job_inputs)- except ValidationError as e:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Invalid source configuration", "details": getattr(e, "detail", str(e))},- )- except Exception as e:- capture_exception(e)- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Failed to load source configuration"},- )-- assert hog_function.inputs is not None- hog_function.inputs = {- **hog_function.inputs,- **{key: {"value": value} for key, value in inputs.items()},- }- hog_function.save(update_fields=["inputs", "encrypted_inputs"])-- success, error = source.webhook_inputs_updated(- config,- get_webhook_url(hog_function.id),- self.team.pk,- inputs,- api_version=source.resolve_api_version(instance.api_version),- )- if not success:- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"success": False, "error": error or "Failed to update webhook on the external source."},- )-- return Response(status=status.HTTP_200_OK, data={"success": True})-- def _fill_default_sync_settings(- self,- source: ExternalDataSource,- schema_updates: list[dict[str, Any]],- source_schemas_by_id: dict[uuid.UUID, ExternalDataSchema],- ) -> tuple[dict[str, tuple[str, str]], set[str]]:- """Fill default sync settings into bulk-update items that ask for them.-- Items with ``apply_sync_defaults`` targeting a schema that has no sync method yet (and- whose update doesn't set one) get their sync settings discovered from the source — one- discovery call for the whole batch. Returns per-schema failures (dropped tables,- webhook-only tables, discovery errors) for the caller to skip and report, plus the ids- of the schemas whose settings were filled in.- """- needing_defaults = [- schema_update- for schema_update in schema_updates- if schema_update.get("apply_sync_defaults")- and schema_update.get("sync_type") is None- and source_schemas_by_id[schema_update["id"]].sync_type is None- ]- # Direct-query sources have no sync method to configure — enabling is just should_sync.- if not needing_defaults or not source.supports_scheduled_sync:- return {}, set()-- failures: dict[str, tuple[str, str]] = {}- names = [source_schemas_by_id[schema_update["id"]].name for schema_update in needing_defaults]- source_impl: AnySource | None = None- try:- source_impl = SourceRegistry.get_source(ExternalDataSourceType(source.source_type))- config = source_impl.parse_config(source.job_inputs)- discovered = source_impl.get_schemas(- config, self.team_id, names=names, api_version=source_impl.resolve_api_version(source.api_version)- )- except Exception as e:- # Discovery connects to the customer's source, so an expected user/upstream failure- # (bad credentials, unreachable host) is theirs to fix and is already reported back to- # them below — don't capture it as error-tracking noise. Mirrors `refresh_schemas`.- _, is_expected_source_error = _classify_refresh_schemas_error(source_impl, e)- if not is_expected_source_error:- capture_exception(e)- reason = "could not read the source to pick default sync settings; check the source credentials"- for schema_update in needing_defaults:- schema = source_schemas_by_id[schema_update["id"]]- failures[str(schema.id)] = (schema.name, reason)- return failures, set()-- # Not every source honors the `names` filter, so match by name instead of order.- discovered_by_name = {discovered_schema.name: discovered_schema for discovered_schema in discovered}- defaulted_schema_ids: set[str] = set()- for schema_update in needing_defaults:- schema = source_schemas_by_id[schema_update["id"]]- discovered_schema = discovered_by_name.get(schema.name)- if discovered_schema is None:- failures[str(schema.id)] = (- schema.name,- "not found on the source; pull new schemas to refresh the table list",- )- continue- if discovered_schema.webhook_only:- failures[str(schema.id)] = (- schema.name,- "can only be synced via webhooks; set up the webhook sync method instead",- )- continue- for key, value in build_default_sync_settings(discovered_schema).items():- # A caller-sent value wins; None (missing or explicit null) means "not set".- if schema_update.get(key) is None:- schema_update[key] = value- defaulted_schema_ids.add(str(schema.id))- return failures, defaulted_schema_ids-- @extend_schema(- request=ExternalDataSourceBulkUpdateSchemasSerializer,- responses={200: ExternalDataSchemaSerializer(many=True)},- )- # The list-shaped response makes the generator add the viewset's search and paging params.- @action(methods=["PATCH"], detail=True, pagination_class=None, filter_backends=[])- def bulk_update_schemas(self, request: Request, *args: Any, **kwargs: Any) -> Response:- source = self.get_object()- serializer = ExternalDataSourceBulkUpdateSchemasSerializer(data=request.data)- serializer.is_valid(raise_exception=True)-- schema_updates: list[dict[str, Any]] = serializer.validated_data["schemas"]- schema_ids = [schema_update["id"] for schema_update in schema_updates]-- if len(set(schema_ids)) != len(schema_ids):- raise ValidationError("Schema updates must contain unique ids")-- source_schemas = ExternalDataSchema.objects.filter(- team_id=self.team_id,- source_id=source.id,- id__in=schema_ids,- ).select_related("source", "table__credential", "table__external_data_source")- source_schemas_by_id = {schema.id: schema for schema in source_schemas}-- if len(source_schemas_by_id) != len(schema_ids):- raise ValidationError("One or more schemas could not be found for this source")-- # Reject up front rather than per-schema, so a batch touching a locked table writes nothing.- self._assert_can_write_schemas(source_schemas_by_id.values())-- # Items that ask for sync defaults on a not-yet-configured schema get them discovered and- # filled in up front. Tables that can't get defaults (dropped from the source, webhook-only)- # fail individually and are skipped below, without blocking the rest of the batch.- failed_schemas, defaulted_schema_ids = self._fill_default_sync_settings(- source, schema_updates, source_schemas_by_id- )- only_validation_errors = True-- serializer_context = self.get_serializer_context()- updated_schemas: list[ExternalDataSchema] = []- # Each deferred action is paired with its schema so a post-commit failure can be attributed.- post_commit_actions: list[tuple[ExternalDataSchema, Callable[[], None]]] = []-- # Validate every payload before writing anything, so a malformed request is rejected up- # front. Some checks only run inside the serializer's update() (during save() below), so- # this catches the common input errors but not all of them — the save loop handles the rest.- prepared: list[tuple[ExternalDataSchema, ExternalDataSchemaSerializer, list[Callable[[], None]]]] = []- for schema_update in schema_updates:- schema_id = schema_update["id"]- schema = source_schemas_by_id[schema_id]- if str(schema.id) in failed_schemas:- continue- schema_payload = {- key: value for key, value in schema_update.items() if key not in ("id", "apply_sync_defaults")- }-- schema_post_commit_actions: list[Callable[[], None]] = []- schema_serializer = ExternalDataSchemaSerializer(- schema,- data=schema_payload,- partial=True,- context={**serializer_context, "post_commit_actions": schema_post_commit_actions},- )- schema_serializer.is_valid(raise_exception=True)- if str(schema.id) in defaulted_schema_ids:- # Defaults discovery already confirmed these tables aren't webhook-only; seed the- # cache so the warm step below doesn't re-probe the source once per schema.- schema_serializer.seed_webhook_only_check(False)- # Do the webhook-only source-discovery call (e.g. Google Ads token refresh + field query)- # here, before the per-schema transaction below. Running it inside update()'s transaction- # held the DB connection idle-in-transaction long enough for the server to close it.- # update() reads the cached result, so it still validates and fails per-schema.- schema_serializer.warm_webhook_only_check(schema)- prepared.append((schema, schema_serializer, schema_post_commit_actions))-- # Commit each schema in its own transaction. A single atomic block around the whole batch- # meant one schema's failure rolled back every schema and failed the request, so the user- # got nothing applied. Isolating per schema keeps the ones that saved committed, attempts- # every schema so a single bad one can't block the rest, and reports the failures together.- for schema, schema_serializer, schema_post_commit_actions in prepared:- try:- with transaction.atomic():- updated_schemas.append(schema_serializer.save())- except Exception as e:- if isinstance(e, ValidationError):- reason = _validation_error_message(e)- logger.warning(- "bulk_update_schemas validation error during save",- source_id=str(source.id),- schema_id=str(schema.id),- )- else:- only_validation_errors = False- reason = "a database error occurred while saving"- capture_exception(e)- logger.exception(- "bulk_update_schemas failed to persist schema",- source_id=str(source.id),- schema_id=str(schema.id),- )- failed_schemas[str(schema.id)] = (schema.name, reason)- # A dropped connection leaves Django holding a dead handle; reset it so the next- # schema reconnects instead of failing on the same broken connection.- if not connection.is_usable():- connection.close()- continue-- # Only run a schema's Temporal side effects once its own row is committed.- post_commit_actions.extend((schema, action) for action in schema_post_commit_actions)-- post_commit_error: Exception | None = None- for action_schema, post_commit_action in post_commit_actions:- try:- post_commit_action()- except Exception as e:- # The row is already committed but its schedule still runs the old cadence. Capture +- # log every failure (with the schema id) so the drift is visible, and remember it so- # the request fails below — the caller must know the batch did not fully apply.- post_commit_error = e- capture_exception(e)- logger.warning(- "bulk_update_schemas saved the schema but its Temporal schedule update failed",- source_id=str(source.id),- schema_id=str(action_schema.id),- exc_info=e,- )-- # Report save failures first so a schedule-update failure can't mask which schemas didn't- # save, then fail the request on the schedule-update failure.- if failed_schemas:- raise BulkSchemaSaveError(failed_schemas, only_validation_errors=only_validation_errors)- if post_commit_error is not None:- raise post_commit_error-- return Response(- ExternalDataSchemaSerializer(updated_schemas, many=True, context=serializer_context).data,- status=status.HTTP_200_OK,- )-- @action(methods=["POST"], detail=True)- def delete_webhook(self, request: Request, *args: Any, **kwargs: Any) -> Response:- instance: ExternalDataSource = self.get_object()-- source_type = ExternalDataSourceType(instance.source_type)- source = SourceRegistry.get_source(source_type)-- if not isinstance(source, WebhookSource):- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "This source type does not support webhooks"},- )-- # Check that no schemas are still relying on the webhook — deleting it- # would break their sync pipeline.- webhook_schemas = ExternalDataSchema.objects.filter(- source=instance,- team_id=self.team_id,- sync_type=ExternalDataSchema.SyncType.WEBHOOK,- should_sync=True,- ).exclude(deleted=True)-- if webhook_schemas.exists():- schema_names = list(webhook_schemas.values_list("name", flat=True))- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={- "message": f"Cannot delete webhook while tables are using webhook sync: {', '.join(schema_names)}. Switch them to full refresh, incremental, or disable syncing first.",- },- )-- if not instance.job_inputs:- # No config means we can't call the external API, but we can still- # clean up the HogFunction.- try:- hog_function = HogFunction.objects.get(- team=self.team,- type="warehouse_source_webhook",- inputs__source_id__value=str(instance.pk),- deleted=False,- )- hog_function.deleted = True- hog_function.enabled = False- hog_function.save(update_fields=["deleted", "enabled"])- except HogFunction.DoesNotExist:- pass-- return Response(- status=status.HTTP_200_OK,- data={"success": True, "external_deleted": False},- )-- try:- config = source.parse_config(instance.job_inputs)- except Exception as e:- capture_exception(e)- return Response(- status=status.HTTP_400_BAD_REQUEST,- data={"message": "Failed to parse source configuration"},- )-- result = delete_webhook_and_hog_function(- team=self.team,- source=source,- config=config,- source_id=str(instance.pk),- api_version=source.resolve_api_version(instance.api_version),- )-- return Response(- status=status.HTTP_200_OK,- data={- "success": result.success,- "external_deleted": result.external_deleted,- "error": result.error,- },- )diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/__init__.py b/products/warehouse_sources/backend/presentation/views/external_data_source/__init__.pynew file mode 100644index 000000000000..8b137891791f--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/__init__.py@@ -0,0 +1 @@+diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/base.py b/products/warehouse_sources/backend/presentation/views/external_data_source/base.pynew file mode 100644index 000000000000..f69dac34aff4--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/base.py@@ -0,0 +1,127 @@+"""Shared ground for the external data source view mixins.++Every mixin resolves its outbound collaborators (logger, error capture, the data warehouse+facade) through this module, so tests have one place to patch them. The mixins also inherit+the typing-only base below, which is what lets each one call across to attributes the+assembled viewset provides at runtime.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from typing import TYPE_CHECKING, Any++import structlog+from psycopg import OperationalError+from rest_framework import viewsets+from rest_framework.request import Request+from rest_framework.response import Response+from sshtunnel import BaseSSHTunnelForwarderError++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.exceptions_capture import capture_exception++from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin+from products.data_warehouse.backend.facade.api import (+ bulk_create_external_data_job_schedules,+ bulk_delete_external_data_schedules,+ cancel_external_data_workflow,+ delete_discover_schemas_schedule,+ delete_external_data_schedule,+ ensure_cdc_slot_cleanup_schedule,+ is_cdc_enabled_for_team,+ is_cdc_extraction_schedule_paused,+ sync_cdc_extraction_schedule,+ sync_discover_schemas_schedule,+ trigger_external_data_source_workflow,+ unpause_cdc_extraction_schedule,+)+from products.revenue_analytics.backend.facade.api import ensure_person_join+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.source_management import (+ AnySource,+ CDCSourceAdapter,+ Config,+ HostNotAllowedError,+ SourceRegistry,+ SourceSchema,+ SSLRequiredError,+ TemporaryHostResolutionError,+ WebhookSource,+ cdc_pg_connection,+ get_primary_key_columns,+ purge_buffer_prefix,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++logger = structlog.get_logger(__name__)++# Failures to reach the source database that only the customer can fix. Handlers return them as a+# 400 without capturing, so they stay out of error tracking.+_EXPECTED_CONNECTION_ERRORS = (+ OperationalError,+ BaseSSHTunnelForwarderError,+ SSLRequiredError,+ HostNotAllowedError,+ TemporaryHostResolutionError,+)++__all__ = [+ "ExternalDataSourceViewSetBase",+ "SourceRegistry",+ "bulk_create_external_data_job_schedules",+ "bulk_delete_external_data_schedules",+ "cancel_external_data_workflow",+ "capture_exception",+ "cdc_pg_connection",+ "delete_discover_schemas_schedule",+ "delete_external_data_schedule",+ "ensure_cdc_slot_cleanup_schedule",+ "ensure_person_join",+ "get_primary_key_columns",+ "is_cdc_enabled_for_team",+ "is_cdc_extraction_schedule_paused",+ "logger",+ "purge_buffer_prefix",+ "sync_cdc_extraction_schedule",+ "sync_discover_schemas_schedule",+ "trigger_external_data_source_workflow",+ "unpause_cdc_extraction_schedule",+]+++if TYPE_CHECKING:++ class ExternalDataSourceViewSetBase(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):+ """The assembled viewset as each mixin sees it. Cross-mixin methods are declared here+ so a mixin can call one another mixin implements without importing it."""++ ordering: str++ def _assert_can_write_schemas(self, schemas: Iterable[ExternalDataSchema]) -> None: ...++ def _auto_register_webhook(+ self,+ source: WebhookSource,+ source_config: Config,+ source_id: str,+ source_schemas: list[SourceSchema],+ permission_errors: Mapping[str, str | None] | None = None,+ ) -> dict | None: ...++ def _setup_cdc_resources(+ self, adapter: CDCSourceAdapter, source_model: ExternalDataSource, payload: dict+ ) -> str | None: ...++ def _validate_source_config_and_credentials(+ self,+ source: AnySource,+ source_type_model: ExternalDataSourceType,+ payload: dict,+ access_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,+ ) -> tuple[Response | None, Config | None]: ...++ def refresh_schemas(self, request: Request, *args: Any, **kwargs: Any) -> Response: ...++else:+ ExternalDataSourceViewSetBase = objectdiff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py b/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.pynew file mode 100644index 000000000000..a4a8b2930869--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/change_data_capture.py@@ -0,0 +1,832 @@+"""Endpoints for change data capture."""++from __future__ import annotations++from typing import Any++from django.db import transaction++from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import serializers, status+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import action++from products.data_warehouse.backend.facade.api import delete_cdc_extraction_schedule+from products.warehouse_sources.backend.facade.models import (+ DataWarehouseTable,+ ExternalDataJob,+ ExternalDataSchema,+ ExternalDataSource,+ update_sync_type_config_keys,+)+from products.warehouse_sources.backend.facade.source_management import (+ DEFAULT_LAG_CRITICAL_THRESHOLD_MB,+ DEFAULT_LAG_WARNING_THRESHOLD_MB,+ CDCRepairError,+ CDCRepairInProgress,+ CDCSourceAdapter,+ PostgresSource,+ get_cdc_adapter,+ repair_cdc_source,+ source_type_supports_cdc,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++from . import base+++class CdcPrerequisitesResponseSerializer(serializers.Serializer):+ valid = serializers.BooleanField(help_text="Whether the source satisfies every CDC prerequisite.")+ errors = serializers.ListField( # type: ignore[assignment] # shadows the DRF `errors` property+ child=serializers.CharField(), help_text="Unmet prerequisites, empty when valid is true."+ )+++class CdcEnableResponseSerializer(serializers.Serializer):+ success = serializers.BooleanField(help_text="Whether CDC was enabled on the source.")+ schedules_ready = serializers.BooleanField(+ help_text=(+ "Whether the extraction and cleanup schedules could be created. False means CDC is enabled but "+ "scheduling failed; the schedule self-heals on the first CDC schema toggle."+ )+ )+++class CdcStatusSerializer(serializers.Serializer):+ enabled = serializers.BooleanField(help_text="Whether CDC is enabled on this source.")++ # Absent when enabled is false — CDC is off, so nothing else is known.+ management_mode = serializers.ChoiceField(+ choices=["posthog", "self_managed"],+ required=False,+ help_text="Who owns the slot and publication: PostHog or the customer.",+ )+ slot_name = serializers.CharField(+ required=False, help_text="Replication slot PostHog consumes from. Empty when unset."+ )+ publication_name = serializers.CharField(+ required=False, help_text="Publication PostHog reads changes from. Empty when unset."+ )+ lag_warning_threshold_mb = serializers.IntegerField(required=False, help_text="Lag in MB above which the UI warns.")+ lag_critical_threshold_mb = serializers.IntegerField(+ required=False, help_text="Lag in MB above which the UI alerts."+ )+ schedule_paused = serializers.BooleanField(+ required=False,+ help_text=(+ "True when a non-retryable failure paused the extraction schedule; the UI then offers Resume instead "+ "of Repair. Degrades to false when the schedule lookup fails."+ ),+ )+ slot_exists = serializers.BooleanField(+ required=False, help_text="Whether the replication slot exists on the source, when the source was reachable."+ )+ publication_exists = serializers.BooleanField(+ required=False, help_text="Whether the publication exists on the source, when the source was reachable."+ )+ lag_bytes = serializers.IntegerField(+ allow_null=True, required=False, help_text="Current slot lag in bytes, when the source was reachable."+ )+ published_tables = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ help_text="Tables in the publication, when the source was reachable and a publication exists.",+ )+++class ExternalDataSourceCDCMixin(base.ExternalDataSourceViewSetBase):+ def _setup_cdc_resources(+ self, adapter: CDCSourceAdapter, source_model: ExternalDataSource, payload: dict+ ) -> str | None:+ """Provision CDC for an existing source by delegating to the engine adapter.++ Writes universal CDC fields (mode, lag thresholds, auto-drop policy) plus the+ adapter-supplied resource fields (slot/publication identifiers, consistent+ point, …) into ``source_model.job_inputs`` and saves. Returns an error string+ on failure, or None on success. Callers decide whether to delete the source+ on failure (create flow does; enable_cdc does not).+ """+ management_mode = payload.get("cdc_management_mode", "posthog")+ base.logger.info(+ "Setting up CDC resources for source",+ source_id=str(source_model.pk),+ source_type=source_model.source_type,+ management_mode=management_mode,+ )++ resource_fields, error = adapter.setup_resources(source_model, payload)+ if error is not None:+ base.logger.warning(+ "CDC resource setup failed",+ source_id=str(source_model.pk),+ source_type=source_model.source_type,+ management_mode=management_mode,+ error=error,+ )+ return error++ base.logger.info(+ "CDC resources provisioned",+ source_id=str(source_model.pk),+ management_mode=management_mode,+ slot_name=resource_fields.get("cdc_slot_name"),+ publication_name=resource_fields.get("cdc_publication_name"),+ resource_keys=sorted(resource_fields.keys()),+ )++ job_inputs = dict(source_model.job_inputs or {})+ job_inputs.update(+ {+ "cdc_enabled": True,+ "cdc_auto_drop_slot": payload.get("cdc_auto_drop_slot", True),+ "cdc_lag_warning_threshold_mb": payload.get(+ "cdc_lag_warning_threshold_mb", DEFAULT_LAG_WARNING_THRESHOLD_MB+ ),+ "cdc_lag_critical_threshold_mb": payload.get(+ "cdc_lag_critical_threshold_mb", DEFAULT_LAG_CRITICAL_THRESHOLD_MB+ ),+ }+ )+ job_inputs.update(resource_fields)+ source_model.job_inputs = job_inputs+ source_model.save(update_fields=["job_inputs", "updated_at"])+ return None++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=CdcPrerequisitesResponseSerializer,+ description="Whether the Postgres database satisfies CDC prerequisites.",+ ),+ 400: OpenApiResponse(description="Invalid config, disallowed host, or connection failure."),+ },+ )+ @action(methods=["POST"], detail=False)+ def check_cdc_prerequisites(self, request: Request, *arg: Any, **kwargs: Any):+ """Validate CDC prerequisites against a live Postgres connection.++ Used by the source wizard to surface ✅/❌ checks before source creation,+ and by the self-managed setup popup to verify user-created publications.+ """+ source_type = request.data.get("source_type")+ if not isinstance(source_type, str) or not source_type_supports_cdc(source_type):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "CDC prerequisite checks are only supported for CDC enabled sources."},+ )++ # Dispatch to the actual source class so subclasses (Supabase, Neon) can run+ # their own pre-connection checks, e.g. rejecting pooled hosts for CDC.+ source_impl = base.SourceRegistry.get_source(ExternalDataSourceType(source_type))+ if not isinstance(source_impl, PostgresSource):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"CDC prerequisite checks are not supported for source type: {source_type}"},+ )+ is_valid, errors = source_impl.validate_config(request.data)+ if not is_valid:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid source config: {', '.join(errors)}"},+ )+ config = source_impl.parse_config(request.data)++ # SSRF protection: reject internal/private hosts (same as validate_credentials).+ is_ssh_valid, ssh_errors = source_impl.ssh_tunnel_is_valid(config, self.team_id)+ if not is_ssh_valid:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": ssh_errors or "SSH tunnel host not allowed"},+ )+ valid_host, host_errors = source_impl.is_database_host_valid(+ config.host,+ self.team_id,+ using_ssh_tunnel=config.ssh_tunnel.enabled if config.ssh_tunnel else False,+ )+ if not valid_host:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": host_errors or "Host not allowed"},+ )++ management_mode = request.data.get("cdc_management_mode", "posthog")+ if management_mode not in ("posthog", "self_managed"):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},+ )++ tables = request.data.get("tables") or []+ slot_name = request.data.get("cdc_slot_name") or None+ publication_name = request.data.get("cdc_publication_name") or None++ try:+ prereq_errors = source_impl.check_cdc_prerequisites(+ config,+ management_mode=management_mode,+ tables=tables,+ slot_name=slot_name,+ publication_name=publication_name,+ team_id=self.team_id,+ )+ except base._EXPECTED_CONNECTION_ERRORS as e:+ # Probing a user-supplied database to validate it is expected to fail when the host,+ # credentials, or SSH tunnel are wrong or the server drops the connection. Surface it+ # to the wizard as a 400, but don't capture it — these are user/upstream connection+ # problems, not bugs in our code, and capturing every one floods error tracking.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to Postgres to check prerequisites: {e}"},+ )+ except Exception as e:+ base.capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to Postgres to check prerequisites: {e}"},+ )++ return Response(+ status=status.HTTP_200_OK,+ data=CdcPrerequisitesResponseSerializer({"valid": len(prereq_errors) == 0, "errors": prereq_errors}).data,+ )++ def _get_cdc_adapter_or_400(self, instance: ExternalDataSource) -> tuple[CDCSourceAdapter | None, Response | None]:+ """Look up the engine adapter for an existing source. Returns 400 if the+ source's type doesn't support CDC."""+ try:+ return get_cdc_adapter(instance), None+ except ValueError:+ return None, Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"CDC is not supported for source type: {instance.source_type}"},+ )++ @action(methods=["POST"], detail=True)+ def check_cdc_prerequisites_for_source(self, request: Request, *arg: Any, **kwargs: Any):+ """Validate CDC prerequisites for an existing source using its stored credentials.++ The detail=False ``check_cdc_prerequisites`` action is for the creation wizard,+ where the client still holds the raw connection config (incl. password) in the+ form. On the Configuration page the source already exists and secret fields are+ stripped from API responses — so the client can't supply them. This reads the+ stored (encrypted) credentials from the DB via the adapter instead.++ Body params: ``cdc_management_mode`` (``"posthog"`` | ``"self_managed"``),+ ``cdc_slot_name`` (optional), ``cdc_publication_name`` (optional).+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None # narrowed by _get_cdc_adapter_or_400++ management_mode = request.data.get("cdc_management_mode", "posthog")+ if management_mode not in ("posthog", "self_managed"):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},+ )++ schema_hint = (instance.job_inputs or {}).get("schema") or "public"+ try:+ prereq_errors = adapter.validate_prerequisites(+ instance,+ management_mode=management_mode,+ tables=[],+ schema=schema_hint,+ slot_name=request.data.get("cdc_slot_name") or None,+ publication_name=request.data.get("cdc_publication_name") or None,+ )+ except base._EXPECTED_CONNECTION_ERRORS as e:+ # Probing the source's database to validate it is expected to fail when the host,+ # credentials, or SSH tunnel are wrong, the server requires/refuses SSL, or it drops the+ # connection. Surface it as a 400, but don't capture it — these are user/upstream+ # connection problems, not bugs in our code, and capturing every one floods error+ # tracking. Mirrors the detail=False check_cdc_prerequisites handler.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to check prerequisites: {e}"},+ )+ except Exception as e:+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to check prerequisites: {e}"},+ )++ return Response(+ status=status.HTTP_200_OK,+ data=CdcPrerequisitesResponseSerializer({"valid": len(prereq_errors) == 0, "errors": prereq_errors}).data,+ )++ @extend_schema(responses=CdcEnableResponseSerializer)+ @action(methods=["POST"], detail=True)+ def enable_cdc(self, request: Request, *arg: Any, **kwargs: Any):+ """Enable CDC on an existing source.++ Provisions engine-side CDC resources via the source's adapter, writes the CDC+ config into ``source.job_inputs``, and ensures the CDC extraction schedule+ exists. Re-runs prereq checks server-side so we never trust a stale+ client-side check.++ Body params: ``cdc_management_mode`` (``"posthog"`` | ``"self_managed"``),+ plus engine-specific identifier hints (e.g. ``cdc_slot_name``,+ ``cdc_publication_name`` for Postgres). Universal tuning fields:+ ``cdc_auto_drop_slot`` (optional bool), ``cdc_lag_warning_threshold_mb``+ (optional int), ``cdc_lag_critical_threshold_mb`` (optional int).+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None # narrowed by _get_cdc_adapter_or_400++ if not base.is_cdc_enabled_for_team(self.team):+ return Response(+ status=status.HTTP_403_FORBIDDEN,+ data={"message": "CDC is not enabled for this team."},+ )++ existing = adapter.parse_cdc_config(instance)+ if existing.enabled:+ return Response(+ status=status.HTTP_409_CONFLICT,+ data={"message": "CDC is already enabled on this source."},+ )++ management_mode = request.data.get("cdc_management_mode", "posthog")+ if management_mode not in ("posthog", "self_managed"):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "cdc_management_mode must be 'posthog' or 'self_managed'."},+ )++ # Validate prerequisites server-side — never trust a client-only check.+ schema_hint = (instance.job_inputs or {}).get("schema") or "public"+ try:+ prereq_errors = adapter.validate_prerequisites(+ instance,+ management_mode=management_mode,+ tables=[],+ schema=schema_hint,+ slot_name=request.data.get("cdc_slot_name") or None,+ publication_name=request.data.get("cdc_publication_name") or None,+ )+ except base._EXPECTED_CONNECTION_ERRORS as e:+ # Expected user/upstream connection failure (bad host/credentials/SSH tunnel, server+ # requires/refuses SSL, dropped connection). Surface as a 400 without capturing — see the+ # check_cdc_prerequisites_for_source handler above.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to check prerequisites: {e}"},+ )+ except Exception as e:+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to check prerequisites: {e}"},+ )++ if prereq_errors:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "CDC prerequisites not met.", "errors": prereq_errors},+ )++ cdc_error = self._setup_cdc_resources(adapter, instance, request.data)+ if cdc_error is not None:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": cdc_error},+ )++ # Ensure the global cleanup schedule exists. There are no CDC schemas yet (the user+ # picks sync_type=cdc per schema afterward), so `base.sync_cdc_extraction_schedule` is a+ # no-op here — the extraction schedule is authoritatively (re)created when a schema is+ # switched to CDC. A failure here therefore can't leave a "CDC on, never runs" state:+ # the slot + config are valid and the schedule self-heals on the first CDC schema+ # toggle. Surface failures (capture, not just log) and flag them in the response.+ schedules_ok = True+ try:+ base.sync_cdc_extraction_schedule(instance, create=True)+ base.ensure_cdc_slot_cleanup_schedule()+ except Exception as e:+ schedules_ok = False+ base.logger.exception("Could not create CDC schedules after enable_cdc", exc_info=e)+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})++ return Response(+ status=status.HTTP_200_OK,+ data=CdcEnableResponseSerializer({"success": True, "schedules_ready": schedules_ok}).data,+ )++ @action(methods=["POST"], detail=True)+ def disable_cdc(self, request: Request, *arg: Any, **kwargs: Any):+ """Disable CDC on an existing source.++ Cancels any running CDC extraction workflow, deletes the extraction schedule,+ delegates engine-side teardown to the source's adapter (drops slot/publication+ for Postgres; equivalent for other engines), clears ``cdc_*`` keys from+ ``job_inputs``, soft-deletes companion CDC tables, and sets all CDC schemas to+ ``sync_type=None``, ``should_sync=False`` so the user must pick a new sync+ strategy before they resume.+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None++ cdc_config = adapter.parse_cdc_config(instance)+ if not cdc_config.enabled:+ return Response(status=status.HTTP_200_OK, data={"success": True, "already_disabled": True})++ # Read the CDC schemas before the sync_type reset below, while they're still+ # marked CDC. Scoped so we don't touch unrelated incremental/full-refresh syncs.+ cdc_schemas = list(+ ExternalDataSchema.objects.filter(+ source=instance,+ sync_type=ExternalDataSchema.SyncType.CDC,+ )+ .exclude(deleted=True)+ .select_related("table")+ )+ # Disabling cancels jobs, drops the slot, purges buffered change data, and resets+ # every CDC schema — editor on the source isn't enough when a table is locked below it.+ self._assert_can_write_schemas(cdc_schemas)+ cdc_schema_ids = [schema.id for schema in cdc_schemas]+ running_jobs = ExternalDataJob.objects.filter(+ pipeline_id=instance.pk,+ team_id=instance.team_id,+ status="Running",+ schema_id__in=cdc_schema_ids,+ ).exclude(workflow_id__isnull=True)+ for running_job in running_jobs:+ if not running_job.workflow_id:+ continue+ try:+ base.cancel_external_data_workflow(running_job.workflow_id)+ except Exception as e:+ base.capture_exception(e, {"source_id": str(instance.id), "workflow_id": running_job.workflow_id})++ # Generic schedule teardown: schedule lives on our side, independent of engine.+ try:+ delete_cdc_extraction_schedule(str(instance.id))+ except Exception:+ base.logger.exception("Failed to delete CDC extraction schedule", extra={"source_id": str(instance.id)})++ # Engine-side teardown: best-effort, never blocks the disable.+ try:+ adapter.cleanup_resources(instance)+ except Exception as e:+ base.logger.exception("Failed engine-side CDC cleanup during disable_cdc", exc_info=e)+ base.capture_exception(e, {"source_id": str(instance.id)})++ # Drop each schema's S3 change buffer: the shadow lane's files are raw customer+ # change data with no consumer once CDC is off, and nothing else expires them.+ for schema_id in cdc_schema_ids:+ base.purge_buffer_prefix(instance.team_id, str(schema_id), base.logger)++ with transaction.atomic():+ # Clear any broken marker (recovery contract): leaving a stale cdc_broken in+ # sync_type_config would make CDC look broken the moment it's re-enabled.+ # Must be inside the atomic block so a failed schema-state reset rolls this back too.+ for schema_id in cdc_schema_ids:+ try:+ update_sync_type_config_keys(+ schema_id, instance.team_id, removes=["cdc_broken", "cdc_extraction_paused"]+ )+ except ExternalDataSchema.DoesNotExist:+ pass++ # Force CDC schemas to pick a new strategy by clearing sync_type and pausing.+ ExternalDataSchema.objects.filter(+ source=instance,+ sync_type=ExternalDataSchema.SyncType.CDC,+ ).exclude(deleted=True).update(sync_type=None, should_sync=False)++ # Soft-delete `_cdc` companion DataWarehouseTable rows so the next sync+ # rebuilds them once the user picks a new strategy.+ DataWarehouseTable.objects.filter(+ external_data_source_id=instance.id,+ team_id=self.team_id,+ deleted=False,+ name__endswith="_cdc",+ ).update(deleted=True)++ # Clear ALL cdc_* keys from job_inputs — leaving stale engine identifiers+ # behind (e.g. `cdc_consistent_point`) would corrupt resume tracking if+ # CDC is later re-enabled.+ job_inputs = dict(instance.job_inputs or {})+ for key in list(job_inputs.keys()):+ if key.startswith("cdc_"):+ job_inputs.pop(key, None)+ instance.job_inputs = job_inputs+ instance.save(update_fields=["job_inputs", "updated_at"])++ return Response(status=status.HTTP_200_OK, data={"success": True})++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response={+ "type": "object",+ "properties": {+ "success": {"type": "boolean"},+ "schemas_reset": {"type": "integer"},+ },+ },+ description="CDC repaired; schemas_reset CDC schemas will fully re-sync.",+ ),+ 400: OpenApiResponse(+ description="CDC not enabled, no active CDC schemas, source looks healthy, or engine-side recreation failed."+ ),+ 409: OpenApiResponse(description="A repair is already running for this source."),+ },+ )+ @action(methods=["POST"], detail=True)+ def repair_cdc(self, request: Request, *arg: Any, **kwargs: Any):+ """Repair CDC on a source whose replication resources were lost.++ Only proceeds on evidence of breakage (a persisted broken marker, or a live probe+ showing the slot/publication missing) — repairing a healthy source would drop its+ slot and force a full re-sync. Cancels running CDC jobs, recreates the engine-side+ slot/publication against the stored CDC config, resets every active CDC schema to+ snapshot mode for a full re-sync (changes since the old slot died are+ unrecoverable), clears the broken markers, and resumes the paused schedules.+ Idempotent: safe to retry after a partial failure. Concurrent repairs of the same+ source are rejected with a 409.+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None # narrowed by _get_cdc_adapter_or_400++ cdc_config = adapter.parse_cdc_config(instance)+ if not cdc_config.enabled:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "CDC is not enabled on this source."},+ )++ try:+ schemas_reset = repair_cdc_source(instance)+ except CDCRepairInProgress as e:+ return Response(status=status.HTTP_409_CONFLICT, data={"message": str(e)})+ except CDCRepairError as e:+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})+ except base._EXPECTED_CONNECTION_ERRORS as e:+ # Expected user/upstream connection failure — surface as a 400 without capturing,+ # mirroring the enable_cdc handler.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to repair CDC: {e}"},+ )+ except Exception as e:+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not repair CDC: {e}"},+ )++ return Response(status=status.HTTP_200_OK, data={"success": True, "schemas_reset": schemas_reset})++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response={"type": "object", "properties": {"success": {"type": "boolean"}}},+ description="CDC resumed; the extraction schedule is unpaused.",+ ),+ 400: OpenApiResponse(+ description="CDC not enabled, the slot/publication were lost (use Repair CDC), the source is still "+ "unreachable, or unpausing failed."+ ),+ },+ )+ @action(methods=["POST"], detail=True)+ def resume_cdc(self, request: Request, *arg: Any, **kwargs: Any):+ """Resume a CDC source whose extraction schedule was paused by a non-retryable+ failure that left the replication slot intact (bad credentials, SSL/host errors).++ Once the user has fixed the root cause, this re-probes the source DB — confirming+ the connection now succeeds and the slot/publication still exist — then unpauses the+ extraction schedule so streaming resumes from where it left off. No re-snapshot, so+ it's the cheap counterpart to Repair CDC. If the slot/publication are actually gone+ (``cdc_broken``, or a live probe showing them missing), resume is refused — only+ Repair CDC can recreate them, at the cost of a full re-sync.+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None # narrowed by _get_cdc_adapter_or_400++ cdc_config = adapter.parse_cdc_config(instance)+ if not cdc_config.enabled:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "CDC is not enabled on this source."},+ )++ cdc_schemas = list(+ ExternalDataSchema.objects.filter(+ source=instance,+ sync_type=ExternalDataSchema.SyncType.CDC,+ should_sync=True,+ ).exclude(deleted=True)+ )+ if not cdc_schemas:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "No schemas are syncing via change data capture, so there is nothing to resume."},+ )++ # A broken source has lost its slot/publication — resuming would just re-fail on the+ # next tick. Route the user to Repair CDC, which recreates them (and re-syncs).+ if any((schema.sync_type_config or {}).get("cdc_broken") for schema in cdc_schemas):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "The replication slot or publication was lost. Use Repair CDC to recreate it."},+ )++ # Re-probe the source: this both re-validates the connection (a still-wrong password+ # raises here) and confirms the slot/publication survive, so we never unpause straight+ # back into the same deterministic failure.+ try:+ live_status = adapter.get_status(instance)+ except base._EXPECTED_CONNECTION_ERRORS as e:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Could not connect to source to resume CDC — check the credentials and try again: {e}"+ },+ )+ except Exception as e:+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to resume CDC: {e}"},+ )++ if live_status.get("slot_exists") is False or live_status.get("publication_exists") is False:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "The replication slot or publication is missing. Use Repair CDC to recreate it."},+ )++ try:+ # Recreate the schedule if it was deleted out-of-band — unpausing a missing schedule is a+ # silent no-op that would report success while CDC never runs (same ordering as CDC repair's+ # _resume_schedules). sync builds an unpaused schedule; the explicit unpause covers the+ # already-existing-but-paused case.+ base.sync_cdc_extraction_schedule(instance)+ base.unpause_cdc_extraction_schedule(str(instance.id))+ except Exception as e:+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not resume CDC: {e}"},+ )++ # Extraction is running again: clear the paused marker so the schema stops reading as+ # halted (failure digest badge, loader status guard). Status stays FAILED until a run+ # actually succeeds. After the unpause, so a failure here leaves the marker for retry.+ for schema in cdc_schemas:+ try:+ update_sync_type_config_keys(schema.id, instance.team_id, removes=["cdc_extraction_paused"])+ except ExternalDataSchema.DoesNotExist:+ pass++ return Response(status=status.HTTP_200_OK, data={"success": True})++ @action(methods=["POST"], detail=True)+ def update_cdc_settings(self, request: Request, *arg: Any, **kwargs: Any):+ """Update CDC tuning fields without enabling/disabling.++ Lets users edit ``cdc_auto_drop_slot``, ``cdc_lag_warning_threshold_mb``, and+ ``cdc_lag_critical_threshold_mb`` independently. These fields are universal+ across engines. Engine-specific identifiers (slot name, management mode, …)+ are immutable post-enable — switching them requires disable + enable.+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None++ cdc_config = adapter.parse_cdc_config(instance)+ if not cdc_config.enabled:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "CDC is not enabled on this source."},+ )++ job_inputs = dict(instance.job_inputs or {})+ updates: dict[str, Any] = {}++ if "cdc_auto_drop_slot" in request.data:+ updates["cdc_auto_drop_slot"] = bool(request.data["cdc_auto_drop_slot"])++ for field in ("cdc_lag_warning_threshold_mb", "cdc_lag_critical_threshold_mb"):+ if field in request.data:+ try:+ value = int(request.data[field])+ except (TypeError, ValueError):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"{field} must be an integer."},+ )+ if value < 1:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"{field} must be >= 1."},+ )+ updates[field] = value++ warn = updates.get("cdc_lag_warning_threshold_mb", job_inputs.get("cdc_lag_warning_threshold_mb"))+ crit = updates.get("cdc_lag_critical_threshold_mb", job_inputs.get("cdc_lag_critical_threshold_mb"))+ if warn is not None and crit is not None and int(warn) >= int(crit):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Warning threshold must be less than critical threshold."},+ )++ if not updates:+ return Response(status=status.HTTP_200_OK, data={"success": True, "unchanged": True})++ job_inputs.update(updates)+ instance.job_inputs = job_inputs+ instance.save(update_fields=["job_inputs", "updated_at"])++ return Response(status=status.HTTP_200_OK, data={"success": True})++ @extend_schema(responses=CdcStatusSerializer)+ @action(methods=["GET"], detail=True)+ def cdc_status(self, request: Request, *arg: Any, **kwargs: Any):+ """Live CDC health for an existing source: slot/publication existence and WAL lag.++ Reads from the source DB via the engine adapter. Returns ``{"enabled": false}``+ when CDC is off, or the stored config plus live ``slot_exists`` /+ ``publication_exists`` / ``lag_bytes`` when on. 400s if the source DB is+ unreachable so the UI can show a degraded/unreachable state.+ """+ instance: ExternalDataSource = self.get_object()++ adapter, err = self._get_cdc_adapter_or_400(instance)+ if err is not None:+ return err+ assert adapter is not None++ cdc_config = adapter.parse_cdc_config(instance)+ if not cdc_config.enabled:+ return Response(status=status.HTTP_200_OK, data=CdcStatusSerializer({"enabled": False}).data)++ try:+ live_status = adapter.get_status(instance)+ except Exception as e:+ # An unreachable source DB is the degraded state this endpoint exists to report, so+ # don't capture expected connection failures as error-tracking noise. Capture only+ # unexpected errors, which point at a bug in our status read.+ if not adapter.is_connection_error(e):+ base.capture_exception(e, {"source_id": str(instance.id), "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to source to read CDC status: {e}"},+ )++ # Paused-but-slot-intact means a non-retryable failure stopped the schedule; the UI offers+ # Resume (vs Repair) so the user can restart without a full re-sync. Best-effort: a Temporal+ # hiccup must not 500 this otherwise DB-only status read, so degrade to not-paused.+ try:+ schedule_paused = base.is_cdc_extraction_schedule_paused(str(instance.id))+ except Exception:+ base.logger.warning("cdc_status_schedule_paused_lookup_failed", source_id=str(instance.id), exc_info=True)+ schedule_paused = False++ return Response(+ status=status.HTTP_200_OK,+ data=CdcStatusSerializer(+ {+ "enabled": True,+ "management_mode": cdc_config.management_mode,+ "slot_name": cdc_config.slot_name,+ "publication_name": cdc_config.publication_name,+ "lag_warning_threshold_mb": cdc_config.lag_warning_threshold_mb,+ "lag_critical_threshold_mb": cdc_config.lag_critical_threshold_mb,+ "schedule_paused": schedule_paused,+ **live_status,+ }+ ).data,+ )diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.pynew file mode 100644index 000000000000..2a0c8fc4d388--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py@@ -0,0 +1,337 @@+"""Serializers and endpoints for source connection options."""++from __future__ import annotations++from typing import Any, cast++from django.db.models import Q++from drf_spectacular.utils import extend_schema, extend_schema_field+from rest_framework import serializers, status+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.hogql.direct_sql.capability import direct_capable_source_types++from posthog.api.utils import action+from posthog.models.user import User+from posthog.permissions import is_service_auth++from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet+from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfig+from products.revenue_analytics.backend.facade.api import remove_person_join+from products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_SOURCE_PREFIX,+ ExternalDataDestination,+ ExternalDataSchema,+ ExternalDataSource,+ ExternalDataSourceDestination,+)+from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType+from products.warehouse_sources.backend.presentation.views.destination_links import (+ DestinationLinkSerializer,+ SourceDestinationsSerializer,+ set_source_destinations,+)+from products.warehouse_sources.backend.presentation.views.public_source_configs import build_source_configs++from . import base, helpers+++class ExternalDataSourceRevenueAnalyticsConfigSerializer(serializers.ModelSerializer):+ class Meta:+ model = ExternalDataSourceRevenueAnalyticsConfig+ fields = ["enabled", "include_invoiceless_charges"]+++class ExternalDataSourceConnectionMetadataSerializer(serializers.Serializer):+ database = serializers.CharField(+ read_only=True,+ required=False,+ allow_null=True,+ help_text="Database name discovered for a direct connection.",+ )+ version = serializers.CharField(+ read_only=True,+ required=False,+ allow_null=True,+ help_text="Database version string reported by the direct connection.",+ )+ engine = serializers.ChoiceField(+ read_only=True,+ required=False,+ allow_null=True,+ choices=helpers.DIRECT_CONNECTION_ENGINE_CHOICES,+ help_text="Backend engine detected for the direct connection.",+ )+ function_source = serializers.CharField(+ read_only=True,+ required=False,+ allow_null=True,+ help_text="System catalog or function source used to discover supported functions.",+ )+ available_functions = serializers.ListField(+ child=serializers.CharField(),+ read_only=True,+ required=False,+ help_text="Functions discovered as available on the direct connection.",+ )+++class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):+ engine = serializers.ChoiceField(+ source="connection_metadata.engine",+ read_only=True,+ allow_null=True,+ choices=helpers.DIRECT_CONNECTION_ENGINE_CHOICES,+ help_text="Backend engine detected for the direct connection.",+ )+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ read_only=True,+ help_text="The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').",+ )+ access_method = serializers.ChoiceField(+ choices=ExternalDataSource.AccessMethod.choices,+ read_only=True,+ help_text="'direct' for pure live-query sources; 'warehouse' for synced sources with direct query enabled.",+ )+ supports_hogql = serializers.SerializerMethodField(+ help_text="Whether HogQL queries compile for this connection. When false, only raw SQL (sendRawQuery) works.",+ )+ is_builtin_managed_warehouse = serializers.SerializerMethodField(+ help_text="Whether this option is the built-in PostHog managed warehouse connection.",+ )+ description = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="User-set description of the source, shown as its display name in the connection picker when set.",+ )++ @extend_schema_field(serializers.BooleanField())+ def get_supports_hogql(self, source: ExternalDataSource) -> bool:+ # Function-local: keeps the direct-SQL driver imports off the django.setup() path.+ from posthog.hogql.direct_sql.capability import direct_supports_hogql # noqa: PLC0415++ return direct_supports_hogql(source)++ @extend_schema_field(serializers.BooleanField())+ def get_is_builtin_managed_warehouse(self, source: ExternalDataSource) -> bool:+ return source.pk == self.context.get("builtin_managed_warehouse_source_id")++ class Meta:+ model = ExternalDataSource+ fields = [+ "id",+ "prefix",+ "engine",+ "source_type",+ "access_method",+ "supports_hogql",+ "is_builtin_managed_warehouse",+ "description",+ ]+ read_only_fields = fields+++class DirectConnectionSourceOptionSerializer(serializers.Serializer):+ """A source type that can be added as a direct (live-query) connection, with display metadata."""++ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ read_only=True,+ help_text="The source type to start a direct-connection setup for (e.g. 'Postgres', 'ClickHouse').",+ )+ label = serializers.CharField( # type: ignore[assignment] # field name intentionally shadows Field.label+ read_only=True,+ help_text="Human-readable name to show in the picker (falls back to the source type).",+ )+ icon_path = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text="Path to the source's icon asset, or null when the source ships no icon.",+ )+++class ExternalDataSourceConnectionOptionsMixin(base.ExternalDataSourceViewSetBase):+ @extend_schema(responses=ExternalDataSourceConnectionOptionSerializer(many=True))+ @action(+ methods=["GET"],+ detail=False,+ pagination_class=None,+ filter_backends=[],+ required_scopes=["external_data_source:read"],+ )+ def connections(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ connection_sources = (+ ExternalDataSource._base_manager.filter(+ team_id=self.team_id,+ source_type__in=direct_capable_source_types(),+ )+ # Pure-direct sources are always live; synced sources only when the toggle is on.+ .filter(Q(access_method=ExternalDataSource.AccessMethod.DIRECT) | Q(direct_query_enabled=True))+ .exclude(deleted=True)+ .only(+ "id",+ "prefix",+ "description",+ "connection_metadata",+ "source_type",+ "access_method",+ )+ .order_by(self.ordering)+ )+ managed_candidates = connection_sources.filter(ExternalDataSource.ready_managed_warehouse_q()).only(+ "id",+ "team_id",+ "prefix",+ "description",+ "connection_metadata",+ "source_type",+ "access_method",+ "direct_query_enabled",+ "job_inputs",+ )+ managed_source = next(+ (source for source in managed_candidates if source.is_dynamic_managed_warehouse),+ None,+ ) or next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)+ if managed_source is not None:+ external_sources = connection_sources.exclude(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)+ else:+ canonical_source = helpers._canonical_legacy_managed_warehouse_source(connection_sources)+ external_sources = helpers._hide_noncanonical_managed_warehouse_sources(+ connection_sources, canonical_source+ )+ if is_service_auth(request):+ accessible_external_sources = external_sources+ else:+ accessible_external_sources = self.user_access_control.filter_queryset_by_access_level(external_sources)+ if not self.user_access_control.has_resource_access(+ "external_data_source"+ ) and not self.user_access_control.has_any_specific_access_for_resource(+ "external_data_source", required_level="viewer"+ ):+ accessible_external_sources = accessible_external_sources.filter(created_by=cast(User, request.user))+ accessible_sources = list(accessible_external_sources)+ options = ([managed_source] if managed_source is not None else []) + accessible_sources++ serializer = ExternalDataSourceConnectionOptionSerializer(+ options,+ many=True,+ context={"builtin_managed_warehouse_source_id": managed_source.pk if managed_source is not None else None},+ )+ return Response(status=status.HTTP_200_OK, data=serializer.data)++ @extend_schema(responses=DirectConnectionSourceOptionSerializer(many=True))+ @action(methods=["GET"], detail=False, pagination_class=None, filter_backends=[])+ def direct_connection_options(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Source types the user can add as a direct connection, driven by the direct-SQL capability+ surface so the picker never drifts from the engines we actually support."""+ direct_types = direct_capable_source_types()+ options = [+ {+ "source_type": source_type,+ "label": config.get("label") or source_type,+ "icon_path": config.get("iconPath"),+ }+ for source_type, config in build_source_configs(include_tables=False).items()+ if source_type in direct_types+ ]+ options.sort(key=lambda option: str(option["label"]).lower())++ serializer = DirectConnectionSourceOptionSerializer(options, many=True)+ return Response(status=status.HTTP_200_OK, data=serializer.data)++ @extend_schema(+ request=DestinationLinkSerializer,+ responses={200: SourceDestinationsSerializer},+ )+ @action(methods=["GET", "PATCH"], detail=True)+ def destinations(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Read or replace the destinations every table on this source syncs to.++ A table with its own override ignores this set until the override is cleared.+ """+ source = self.get_object()++ if request.method == "GET":+ attached = [+ str(link.destination_id)+ for link in ExternalDataSourceDestination.objects.for_team(self.team_id)+ .filter(source_id=source.id, enabled=True)+ .exclude(destination__deleted=True)+ ]+ # A source nobody configured has no links but is not syncing nowhere: it syncs to the+ # PostHog warehouse. Report where it actually goes, or the picker shows every+ # destination off and saving from that state silently drops the warehouse.+ # Looked up rather than resolved, because `resolve_destinations` creates the+ # warehouse row on demand and a GET must not write.+ if not attached:+ warehouse = (+ ExternalDataDestination.objects.for_team(self.team_id)+ .filter(type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE, deleted=False)+ .first()+ )+ attached = [str(warehouse.id)] if warehouse else []+ return Response(+ status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).data+ )++ serializer = DestinationLinkSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ # Editor on the source isn't enough on its own: this replaces the destination set every+ # table without its own override inherits, and (like `destroy`) never resolves a schema+ # through DRF's object permissions, so a table locked below the source would otherwise be+ # rerouted to a destination its editor never had access to.+ schemas = list(+ ExternalDataSchema.objects.exclude(deleted=True)+ .filter(team_id=self.team_id, source_id=source.id)+ .select_related("table")+ )+ self._assert_can_write_schemas(schemas)++ attached = set_source_destinations(+ team_id=self.team_id,+ source_id=source.id,+ destination_ids=serializer.validated_data["destination_ids"],+ )+ return Response(+ status=status.HTTP_200_OK, data=SourceDestinationsSerializer({"destination_ids": attached}).data+ )++ @action(methods=["PATCH"], detail=True)+ def revenue_analytics_config(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Update the revenue analytics configuration and return the full external data source."""+ external_data_source = self.get_object()+ config = external_data_source.revenue_analytics_config_safe++ config_serializer = ExternalDataSourceRevenueAnalyticsConfigSerializer(config, data=request.data, partial=True)+ config_serializer.is_valid(raise_exception=True)+ config_serializer.save()++ table_prefix = external_data_source.prefix or ""++ if config.enabled:+ managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(+ team=self.team,+ kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,+ )+ managed_viewset.sync_views()+ base.ensure_person_join(self.team.pk, table_prefix)+ else:+ try:+ managed_viewset = DataWarehouseManagedViewSet.objects.get(+ team=self.team,+ kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,+ )+ managed_viewset.delete_with_views()++ except DataWarehouseManagedViewSet.DoesNotExist:+ pass+ remove_person_join(self.team.pk, table_prefix)++ # Return the full external data source with updated config+ source_serializer = self.get_serializer(external_data_source, context=self.get_serializer_context())+ return Response(source_serializer.data)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/credential_store.py b/products/warehouse_sources/backend/presentation/views/external_data_source/credential_store.pynew file mode 100644index 000000000000..82c455c4817c--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/credential_store.py@@ -0,0 +1,294 @@+"""Serializers and endpoints for stored credentials."""++from __future__ import annotations++import dataclasses+from typing import Any, cast+from urllib.parse import quote++from django.conf import settings+from django.utils import timezone++from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import serializers, status+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import action+from posthog.models.user import User++from products.warehouse_sources.backend.facade.models import PendingSourceCredential+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++from . import base+++class SourceConnectLinkSerializer(serializers.Serializer):+ source_type = serializers.CharField(help_text="The source type the link is for.")+ auth_method = serializers.ChoiceField(+ choices=["oauth", "credentials"],+ help_text=(+ "What the user will do on the connect page: 'oauth' = authorize an account in their browser; "+ "'credentials' = enter connection details (or pick OAuth where the source offers both). Either "+ "way secrets never pass through the agent, and the result is always a stored credential id."+ ),+ )+ connect_url = serializers.CharField(+ help_text=(+ "Full URL to share with the user. It opens the source's connection form in PostHog — "+ "credentials never pass through the agent or the chat."+ )+ )+ instructions = serializers.CharField(help_text="Next steps for the agent to relay to the user.")+++class SourceCredentialCreateSerializer(serializers.Serializer):+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type these credentials are for (e.g. 'Stripe', 'Postgres').",+ )+ payload = serializers.DictField(+ help_text=(+ "Connection details as flat keys for the source_type — the same fields the create flow accepts "+ "(host, port, password, API key, …). Checked against a live connection before being stored."+ ),+ )+++class SourceCredentialSerializer(serializers.Serializer):+ credential_id = serializers.UUIDField(+ help_text="Stored credential id. Pass to the setup endpoint as {'credential_id': <id>} to create the source."+ )+ source_type = serializers.CharField(help_text="The source type the stored credentials are for.")+ created_at = serializers.DateTimeField(help_text="When the credentials were stored.")+ expires_at = serializers.DateTimeField(+ help_text="When the stored credentials expire. Unconsumed credentials are unusable past this time."+ )+++def _find_unresolved_secret_refs(payload: Any) -> list[str]:+ """Return payload keys whose value is an unresolved secret reference.++ The wizard CLI's `wizard_ask` returns sensitive answers as `{"secretRef": "..."}` objects that the+ caller must resolve to real values before they reach PostHog. If one slips through, source creation+ fails downstream with a confusing "invalid credentials"/"invalid API key" error — detect it up front+ so the agent gets an actionable message instead.+ """+ if not isinstance(payload, dict):+ return []+ return [key for key, value in payload.items() if isinstance(value, dict) and "secretRef" in value]+++def _unresolved_secret_ref_response(payload: Any) -> Response | None:+ offenders = _find_unresolved_secret_refs(payload)+ if not offenders:+ return None+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": (+ f"Unresolved secret reference(s) for: {', '.join(sorted(offenders))}. These fields are still "+ "`{'secretRef': ...}` objects — PostHog cannot resolve them. Resolve the secret to its real "+ "value before calling (or collect credentials via data-warehouse-source-connect-link and pass "+ "the resulting credential_id instead)."+ )+ },+ )+++def _find_top_level_oauth_field(config: dict) -> dict | None:+ """Find a top-level OAuth field ({type: 'oauth', kind, name, ...}) in a source config dump.++ Only a top-level OAuth field makes a source OAuth-only (e.g. Hubspot). An OAuth option+ nested inside a select (e.g. Stripe's auth_method) coexists with credential options, so+ those sources route to the credentials connect page — its form still offers the OAuth+ choice alongside API keys.+ """+ for field in config.get("fields") or []:+ if isinstance(field, dict) and field.get("type") == "oauth" and field.get("kind"):+ return field+ return None+++class DatabaseSchemaRequestSerializer(serializers.Serializer):+ """Validate credentials and preview available tables from a remote database.++ The request body contains source_type plus flat source-specific credential fields+ (e.g. host, port, database, user, password, schema for Postgres). The credential+ fields vary per source_type and are validated dynamically by the source registry.++ For source_type "Custom" (a user-defined REST API) the body carries `manifest_json`+ (a stringified RESTAPIConfig describing client.base_url, auth, and resources) plus the+ credential for the manifest's declared auth type — `auth_token` (bearer), `auth_api_key`+ (api_key), or `auth_password` (http_basic); keep secrets in these auth_* keys, never+ inline in manifest_json. The returned tables mirror the manifest's resources, with+ detected primary keys and incremental cursors.+ """++ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type to validate against.",+ )++[email protected](frozen=True, kw_only=True, slots=True)+class ResolvedStoredCredential:+ payload: dict = dataclasses.field(repr=False)+ credential: PendingSourceCredential | None+ error_response: Response | None+++class ExternalDataSourceCredentialStoreMixin(base.ExternalDataSourceViewSetBase):+ @extend_schema(+ request=SourceCredentialCreateSerializer,+ responses={201: SourceCredentialSerializer},+ )+ @action(methods=["POST"], detail=False)+ def store_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Validate and store credentials for a data warehouse source without creating the source.++ Backs the source connect page: the user enters credentials directly in PostHog, they are+ checked against a live connection, then stashed encrypted in a temporary store. The returned+ credential id can be passed to `setup` as {'credential_id': <id>} to create the source — so+ secrets never travel through an agent conversation. The stash is single-use: it is deleted+ as soon as `setup` consumes it, and expires after 24 hours if never consumed.+ """+ serializer = SourceCredentialCreateSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ source_type = serializer.validated_data["source_type"]+ payload = dict(serializer.validated_data["payload"])++ for key, value in payload.items():+ if isinstance(value, str):+ payload[key] = value.strip()++ source_type_model = ExternalDataSourceType(source_type)+ source = base.SourceRegistry.get_source(source_type_model)++ error_response, _ = self._validate_source_config_and_credentials(source, source_type_model, payload)+ if error_response is not None:+ return error_response++ # Opportunistically purge expired stashes — there is no separate cleanup job.+ PendingSourceCredential.objects.for_team(self.team_id).filter(expires_at__lte=timezone.now()).delete()++ credential = PendingSourceCredential.objects.create(+ team_id=self.team_id,+ source_type=source_type,+ payload=payload,+ created_by=cast(User, request.user),+ )++ return Response(+ status=status.HTTP_201_CREATED,+ data=SourceCredentialSerializer(+ {+ "credential_id": credential.id,+ "source_type": source_type,+ "created_at": credential.created_at,+ "expires_at": credential.expires_at,+ }+ ).data,+ )++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Only return stored credentials for this source type (e.g. 'Stripe', 'Postgres').",+ )+ ],+ responses=SourceCredentialSerializer(many=True),+ )+ @action(methods=["GET"], detail=False, pagination_class=None)+ def stored_credentials(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List credentials the requesting user stored via the source connect page that haven't been consumed yet.++ Returns metadata only (id, source type, timestamps) — never the secrets themselves. Stored+ credentials are scoped to their creator: only the user who filled the connect page can list+ or consume them. They are temporary too: they disappear once consumed by `setup` or when+ they expire. Newest first, so after a user confirms they've finished the connect page, the+ first entry for the source type is the one to pass to `setup`.+ """+ queryset = (+ PendingSourceCredential.objects.for_team(self.team_id)+ .filter(created_by=cast(User, request.user), expires_at__gt=timezone.now())+ .order_by("-created_at")+ )+ source_type = request.query_params.get("source_type")+ if source_type:+ queryset = queryset.filter(source_type=source_type)++ data = [+ {+ "credential_id": credential.id,+ "source_type": credential.source_type,+ "created_at": credential.created_at,+ "expires_at": credential.expires_at,+ }+ for credential in queryset+ ]+ return Response(status=status.HTTP_200_OK, data=SourceCredentialSerializer(data, many=True).data)++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=True,+ description="The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').",+ )+ ],+ responses=SourceConnectLinkSerializer,+ )+ @action(methods=["GET"], detail=False)+ def connect_link(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Return a secure browser link for connecting a data warehouse source.++ The link opens a minimal connect page rendering the source's full connection form — OAuth options+ included — with no table selection and no source creation. The user authenticates in their browser,+ secrets never pass through the agent, and the agent finishes setup afterwards by passing the stored+ credential id to data-warehouse-source-setup.+ """+ source_type = request.query_params.get("source_type")+ if not source_type:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Missing required parameter: source_type"},+ )+ try:+ source_type_model = ExternalDataSourceType(source_type)+ except ValueError:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Unknown source_type '{source_type}'"},+ )++ source = base.SourceRegistry.get_source(source_type_model)+ oauth_field = _find_top_level_oauth_field(source.get_source_config.model_dump())+ action_phrase = (+ f"connect their {source_type} account" if oauth_field else f"enter their {source_type} connection details"+ )++ data = {+ "source_type": source_type,+ "auth_method": "oauth" if oauth_field else "credentials",+ "connect_url": (+ f"{settings.SITE_URL}/project/{self.team_id}/data-warehouse/connect?kind={quote(str(source_type))}"+ ),+ "instructions": (+ f"Share this link with the user. They {action_phrase} directly in PostHog — never ask them to "+ "paste credentials or tokens into the chat. The page only stores the connection details; it does "+ "not create the source. Once the user confirms they're done, find the stored credential id via "+ f"data-warehouse-stored-credentials-list (source_type='{source_type}', newest first) and call "+ 'data-warehouse-source-setup with {"credential_id": <id>} in the payload. Stored credentials are '+ "single-use, expire after 24 hours, and are only visible to and consumable by the PostHog user "+ "who entered them — so the page must be filled by the same user this session authenticates as."+ ),+ }+ return Response(status=status.HTTP_200_OK, data=SourceConnectLinkSerializer(data).data)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.pynew file mode 100644index 000000000000..5b9f81c63eb0--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py@@ -0,0 +1,539 @@+"""Helpers for external data source API requests."""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from typing import Any++from django.db.models import Q, QuerySet++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception++from products.data_warehouse.backend.facade.api import (+ DirectQueryEngine,+ apply_on_refresh as apply_sql_warehouse_refresh_migration,+ get_postgres_source_location,+ is_multi_schema_capable_sql_source,+ source_namespace_is_blank,+)+from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX, ExternalDataSource+from products.warehouse_sources.backend.facade.source_config import (+ SourceFieldFileUploadConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,+ SourceFieldOauthConfig,+ SourceFieldSelectConfig,+ SourceFieldSSHTunnelConfig,+ SourceFieldSwitchGroupConfig,+)+from products.warehouse_sources.backend.facade.source_management import (+ DATABASE_HOST_NOT_ALLOWED_GUIDANCE,+ AnySource,+ Config,+ FieldType,+ SourceSchema,+ source_requires_ssl,+)+from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode++REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE = "Could not fetch schemas from source."++RESERVED_SOURCE_NAME_MESSAGE = "This source name is reserved by PostHog."++INVALID_CREDENTIALS_FALLBACK_MESSAGE = (+ "We couldn't validate those credentials. Check they're correct and have the required access, then try again."+)+++def _source_unavailable_message(source_type: str) -> str:+ # A source with no schema discovery is an unreleased scaffold the UI normally hides. Tell the+ # user it isn't ready rather than exposing the internal "schema discovery" wording.+ return (+ f"The {source_type} source isn't available to connect yet. "+ "Choose a different source, or contact support if you were expecting it."+ )+++def _canonical_legacy_managed_warehouse_source(+ queryset: QuerySet[ExternalDataSource],+) -> ExternalDataSource | None:+ candidates = (+ queryset.select_related(None)+ .filter(ExternalDataSource.legacy_managed_warehouse_q())+ .only(+ "id",+ "team_id",+ "created_at",+ "prefix",+ "connection_metadata",+ "source_type",+ "access_method",+ "direct_query_enabled",+ "job_inputs",+ )+ .order_by("-created_at")+ )+ return next(+ (source for source in candidates if source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL),+ None,+ )+++def _hide_noncanonical_managed_warehouse_sources(+ queryset: QuerySet[ExternalDataSource], canonical_source: ExternalDataSource | None+) -> QuerySet[ExternalDataSource]:+ hidden_sources = Q(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)+ if canonical_source is not None:+ hidden_sources &= ~Q(pk=canonical_source.pk)+ return queryset.exclude(hidden_sources)+++REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {+ "timeout": "Connection timed out while fetching schemas from the source.",+ "timed out": "Connection timed out while fetching schemas from the source.",+ "connection refused": "Could not connect to the source. Check the host, port, and network access.",+ "could not connect": "Could not connect to the source. Check the host, port, and network access.",+ "could not translate host name": "Could not resolve the source host.",+ "name or service not known": "Could not resolve the source host.",+ "network is unreachable": "Could not reach the source network.",+ "no route to host": "Could not reach the source host.",+ "access denied": "Could not authenticate with the source. Check the connection credentials.",+ "authentication failed": "Could not authenticate with the source. Check the connection credentials.",+ "password authentication failed": "Could not authenticate with the source. Check the connection credentials.",+ "unauthorized": "Could not authenticate with the source. Check the connection credentials.",+ "forbidden": "The source credentials do not have permission to fetch schemas.",+ "ssl/tls connection is required": "SSL/TLS is required to connect to the source.",+ "could not establish session to ssh gateway": "Could not establish an SSH tunnel to the source.",+ # Raised by the connect-time host check of every SQL source; the map is matched on lowercased text.+ "database host not allowed": DATABASE_HOST_NOT_ALLOWED_GUIDANCE,+ "temporary failure resolving": "Could not resolve the source host right now. Try again in a moment.",+}+++def _exception_text(error: Exception) -> str:+ message = " ".join(str(arg) for arg in error.args if arg is not None) or str(error)+ return f"{type(error).__name__}: {message}"+++def _classify_refresh_schemas_error(source: AnySource | None, error: Exception) -> tuple[str, bool]:+ error_text = _exception_text(error)+ normalized_error_text = error_text.lower()+ matched_source_error = False++ if source is not None:+ for pattern, friendly_message in source.get_non_retryable_errors().items():+ if pattern and pattern.lower() in normalized_error_text:+ if friendly_message:+ return friendly_message, True+ matched_source_error = True++ for pattern, friendly_message in REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES.items():+ if pattern in normalized_error_text:+ return friendly_message, True++ if matched_source_error:+ return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, True++ return REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE, False+++def _credentials_validation_failed(source: AnySource, team_id: int, error: Exception) -> tuple[bool, str | None]:+ """Fallback result for an *unexpected* exception raised by a source's credential probe.++ Sources are expected to catch their own errors and return ``(False, message)``. One that raises+ instead would 500 the create/update request and show someone mid-onboarding an opaque server+ error, so capture it for us and hand back an actionable message — the same treatment schema+ discovery already gives an unexpected error just below the credential check."""+ capture_exception(error, {"source_type": str(source.source_type), "team_id": team_id})+ return False, INVALID_CREDENTIALS_FALLBACK_MESSAGE+++def get_sensitive_field_names(fields: list[FieldType]) -> set[str]:+ """Extract field names that contain sensitive data from a source config's fields."""+ return get_nonsensitive_and_sensitive_field_names(fields).sensitive+++def get_oauth_integration_kinds(fields: list[FieldType]) -> set[str]:+ """The integration kinds a source connects with, declared by its `oauth` fields (`kind`) and its+ `oauth-account-select` fields (`integrationKind`). Every OAuth account listing is served by one+ endpoint that takes an integration id from the caller, so this is what the endpoint checks that id+ against — a Google integration id must not be able to route its token into the LinkedIn Ads client+ just because both rows belong to the caller's team.++ Both field types are read because a source can list accounts without rendering a picker: GitHub+ serves repositories to its own component off a plain `oauth` field."""+ kinds: set[str] = set()+ for field in fields:+ if isinstance(field, SourceFieldOauthAccountSelectConfig):+ kinds.add(field.integrationKind)+ elif isinstance(field, SourceFieldOauthConfig):+ kinds.add(field.kind)+ elif isinstance(field, SourceFieldSwitchGroupConfig):+ kinds.update(get_oauth_integration_kinds(field.fields))+ elif isinstance(field, SourceFieldSelectConfig):+ for option in field.options:+ if option.fields:+ kinds.update(get_oauth_integration_kinds(option.fields))+ return kinds+++def _name_variants(name: str) -> tuple[str, ...]:+ """The spellings a declared field name can be stored under, declared spelling first.++ Source field names may use hyphens (e.g. "temporary-dataset") while+ dataclasses.asdict() persists the snake_case field name ("temporary_dataset").+ """+ normalised = name.replace("-", "_")+ return (name,) if normalised == name else (name, normalised)+++def _add_name_variants(target: set[str], name: str) -> None:+ """Add a field name and its underscore variant to a set.++ We need to recognise both forms when classifying persisted job_inputs.+ """+ target.update(_name_variants(name))+++def _stored_key(data: Mapping[str, Any], name: str) -> str | None:+ """The key `data` holds a declared field under, or None when it holds neither spelling.++ Prefers the declared spelling when both are present, matching how config parsing+ resolves the alias.+ """+ return next((key for key in _name_variants(name) if key in data), None)+++def _stored_value(data: Mapping[str, Any], name: str) -> Any:+ """The value `data` holds for a declared field under either spelling."""+ key = _stored_key(data, name)+ return data[key] if key is not None else None+++@frozen+class DeclaredFieldNames:+ """Declared field names that need special handling when reading or merging job_inputs.++ `hyphenated` are names the source declares with a hyphen. `dataclasses.asdict()` persists+ the Python attribute name instead, so stored configs can hold either spelling.+ `switch_groups` are switch-group container names, whose stored value is a nested dict.+ """++ hyphenated: set[str]+ switch_groups: set[str]+++def get_declared_field_names(fields: list[FieldType]) -> DeclaredFieldNames:+ """Collect hyphenated and switch-group field names, flattened across all nesting levels."""+ hyphenated: set[str] = set()+ switch_groups: set[str] = set()++ for field in fields:+ if "-" in field.name:+ hyphenated.add(field.name)+ if isinstance(field, SourceFieldSwitchGroupConfig):+ switch_groups.add(field.name)+ nested = get_declared_field_names(field.fields)+ hyphenated.update(nested.hyphenated)+ switch_groups.update(nested.switch_groups)+ elif isinstance(field, SourceFieldSelectConfig):+ for option in field.options:+ if option.fields:+ nested = get_declared_field_names(option.fields)+ hyphenated.update(nested.hyphenated)+ switch_groups.update(nested.switch_groups)++ return DeclaredFieldNames(hyphenated=hyphenated, switch_groups=switch_groups)+++def restore_declared_field_names(data: dict, hyphenated: set[str]) -> dict:+ """Return a copy of data re-keyed to the names the source config declares.++ A hyphenated field round-trips through `dataclasses.asdict()`, which writes the Python+ attribute name ("temporary_dataset") rather than the declared one ("temporary-dataset").+ Clients key off the declared name, so restore it. When both spellings are present the+ declared one wins, matching how config parsing prefers the alias.+ """+ if not hyphenated:+ return data++ variants = {name.replace("-", "_"): name for name in hyphenated}+ result: dict = {}+ for key, value in data.items():+ declared = variants.get(key)+ if declared is not None:+ if declared in data:+ continue+ key = declared+ if isinstance(value, dict):+ value = restore_declared_field_names(value, hyphenated)+ result[key] = value+ return result+++@frozen+class FieldSensitivitySplit:+ nonsensitive: set[str]+ sensitive: set[str]+++def get_nonsensitive_and_sensitive_field_names(fields: list[FieldType]) -> FieldSensitivitySplit:+ """Classify source config field names as nonsensitive or sensitive.++ Returns the field-name sets flattened across all nesting levels.+ """+ nonsensitive: set[str] = set()+ sensitive: set[str] = set()++ for field in fields:+ if isinstance(field, SourceFieldInputConfig):+ if field.type == SourceFieldInputConfigType.PASSWORD or field.secret:+ _add_name_variants(sensitive, field.name)+ else:+ _add_name_variants(nonsensitive, field.name)+ elif isinstance(field, SourceFieldFileUploadConfig):+ _add_name_variants(sensitive, field.name)+ elif isinstance(field, SourceFieldSelectConfig):+ _add_name_variants(nonsensitive, field.name)+ for option in field.options:+ if option.fields:+ nested = get_nonsensitive_and_sensitive_field_names(option.fields)+ nonsensitive.update(nested.nonsensitive)+ sensitive.update(nested.sensitive)+ elif isinstance(field, SourceFieldSwitchGroupConfig):+ _add_name_variants(nonsensitive, field.name)+ nested = get_nonsensitive_and_sensitive_field_names(field.fields)+ nonsensitive.update(nested.nonsensitive)+ sensitive.update(nested.sensitive)+ elif isinstance(field, SourceFieldOauthConfig | SourceFieldOauthAccountSelectConfig):+ # The selected account/property is a plain identifier (e.g. Bing Ads account_id,+ # GSC site_url), not a secret — keep it so the form can prefill on edit.+ _add_name_variants(nonsensitive, field.name)+ elif isinstance(field, SourceFieldSSHTunnelConfig):+ _add_name_variants(nonsensitive, field.name)+ # SSH tunnel has a known nested structure not declared in the field tree.+ # "auth"/"auth_type" are container keys for SSHTunnelAuthConfig.+ nonsensitive.update({"host", "port", "username", "auth", "auth_type", "require_tls"})+ sensitive.update({"password", "passphrase", "private_key"})++ return FieldSensitivitySplit(nonsensitive=nonsensitive, sensitive=sensitive)+++# Config metadata keys that are always safe to include in nested dicts+_CONFIG_META_KEYS = {"selection", "enabled"}++# CDC config lives in job_inputs but isn't part of any source's user-facing form field+# tree, so it would otherwise be stripped from API reads as "unknown". None of these are+# secrets — they're operational config the Configuration page needs to render CDC state.+_CDC_EXPOSED_JOB_INPUT_KEYS = {+ "cdc_enabled",+ "cdc_management_mode",+ "cdc_slot_name",+ "cdc_publication_name",+ "cdc_auto_drop_slot",+ "cdc_lag_warning_threshold_mb",+ "cdc_lag_critical_threshold_mb",+ "cdc_consistent_point",+ # Set by migrate_cdc_source_to_buffered, never by the API. Losing it on an unrelated PATCH+ # would resume legacy delivery from an advanced slot and strand the unread buffer.+ "cdc_ingest_mode",+}+++def strip_sensitive_from_dict(data: dict, nonsensitive: set[str], sensitive: set[str]) -> dict:+ """Return a copy of data with sensitive and unknown keys removed.++ Keys in the nonsensitive set or config metadata keys are kept.+ Keys in the sensitive set or not in any known set are stripped.+ Nested dicts are processed recursively.+ """+ result: dict = {}+ for key, value in data.items():+ if key in sensitive:+ continue+ if key not in nonsensitive and key not in _CONFIG_META_KEYS:+ continue+ if isinstance(value, dict):+ result[key] = strip_sensitive_from_dict(value, nonsensitive, sensitive)+ else:+ result[key] = value+ return result+++# Fields whose change could redirect the database connection to a different server+# (and therefore exfiltrate credentials via a poisoned SSH tunnel — VERIA-311).+_SSH_TUNNEL_CONNECTION_FIELDS = ("enabled", "host", "port")++# Top-level job_input fields that name the connection target. Changing any of them+# repoints the source at a different server, so preserved credentials must not be+# reused without re-entry (e.g. ServiceNow's `instance_url` could otherwise be swapped+# to an attacker host that then receives the stored API key / password — VERIA-311).+_CONNECTION_TARGET_FIELDS = ("host", "instance_url")+++def _coerce_connection_target(value: Any) -> str:+ """Normalize a connection-target value for comparison.++ Scalars are coerced to strings to ignore type drift between stored values+ (often strings) and JSON-parsed input (bools/ints). Only `None` collapses to ""+ — `or ""` would also swallow falsy-but-meaningful values like `False` and 0,+ making stored "False" falsely diverge from JSON `false`.+ """+ return "" if value is None else str(value)+++def connection_target_changed(existing: Any, incoming: Any) -> bool:+ """True if a named connection-target field actually moved to a different target.++ An unset field and a blank one name the same (absent) target, so collapsing them keeps the+ gate off an edit that changes nothing: the edit form submits a blank for every declared field+ the stored source never had, and treating that as a retarget blocks the whole form behind a+ credential re-entry that does not apply.+ """+ return _coerce_connection_target(existing) != _coerce_connection_target(incoming)+++def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:+ """True if the SSH tunnel's connection target (enabled/host/port) changed."""+ existing = existing if isinstance(existing, dict) else {}+ incoming = incoming if isinstance(incoming, dict) else {}++ return any(connection_target_changed(existing.get(key), incoming.get(key)) for key in _SSH_TUNNEL_CONNECTION_FIELDS)+++# Nested containers that keep their secrets one level down, not at the top level: the+# SourceFieldSelectConfig ones (Stripe `auth_method`, Snowflake `auth_type`, ServiceNow+# `auth_method`) key their selected branch as `selection`; the SourceFieldSwitchGroupConfig+# one (Billomat's `registered_app`) keys it as `enabled` instead, but the same carried-over-+# secret check below applies either way.+_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type", "registered_app")++# Secrets the edit form can never re-supply (parsed into the individual fields on create, then+# stripped from API reads and hidden in the edit form), so gating credential re-entry on them would+# permanently block host changes. Excluded from the gate but still preserved by the merge: MongoDB+# connects via `connection_string`, while SQL sources use the individual fields and gate `password`.+_CREATION_ONLY_SECRET_FIELDS = frozenset({"connection_string"})+++def has_preserved_credentials(+ existing: dict[str, Any],+ incoming: dict[str, Any],+ sensitive_fields: set[str],+ nested_containers: Iterable[str] = _NESTED_AUTH_CONTAINERS,+) -> bool:+ """True if any stored secret would be reused because the update didn't re-supply it.++ Checks both top-level secret fields and the nested containers where sources like+ ServiceNow, Stripe and Snowflake keep their credentials. Used to force credential+ re-entry when the connection target changes, so a redirected host can't receive a+ preserved secret. A secret only counts as preserved when it would survive the merge:+ an absent container carries the whole existing block over, a same-selection container+ preserves any field the update omits, and a selection switch replaces the block wholesale.++ Switch groups merge the same way, so callers pass their names too. A switch group carries+ no `selection`, which reads as unchanged and lands on the omitted-field check — the branch+ that matches how the merge treats them. A group declared with a hyphen can be stored under+ either spelling, so containers are resolved the same way the merge resolves them.+ """+ if any(existing.get(key) and not incoming.get(key) for key in sensitive_fields):+ return True++ for container_key in nested_containers:+ existing_container = _stored_value(existing, container_key)+ if not isinstance(existing_container, dict):+ continue+ incoming_container = _stored_value(incoming, container_key)+ if not isinstance(incoming_container, dict):+ # Container not re-supplied — the existing secrets carry over wholesale.+ if any(existing_container.get(key) for key in sensitive_fields):+ return True+ continue+ if existing_container.get("selection") != incoming_container.get("selection"):+ continue+ if any(existing_container.get(key) and not incoming_container.get(key) for key in sensitive_fields):+ return True++ return False+++def get_direct_connection_metadata(+ *,+ source_impl: Any,+ source_config: Config,+ team_id: int,+ source_model: ExternalDataSource | None = None,+ fallback: dict[str, Any] | None = None,+) -> dict[str, Any]:+ metadata_fetcher = getattr(source_impl, "get_connection_metadata", None)+ if not callable(metadata_fetcher):+ return fallback or {}++ require_ssl = source_model is not None and source_requires_ssl(source_model, source_config)++ try:+ metadata = metadata_fetcher(source_config, team_id, require_ssl=require_ssl)+ except Exception as error:+ # Connection metadata is best-effort — we fall back below regardless. An expected+ # user/upstream connection failure (unreachable or misconfigured host, refused connection,+ # bad credentials) is the customer's to fix and is already surfaced by credential+ # validation, so don't capture it as error-tracking noise. Mirrors `refresh_schemas`.+ _, is_expected_source_error = _classify_refresh_schemas_error(source_impl, error)+ if not is_expected_source_error:+ capture_exception(error)+ return fallback or {}++ return metadata if isinstance(metadata, dict) else (fallback or {})+++def get_postgres_source_table_location(+ *,+ schema_name: str,+ source_schema: SourceSchema | None,+ default_schema: str | None,+) -> tuple[str | None, str, str]: # nosemgrep: tuple-return-prefer-dataclass -- grandfathered backlog+ return get_postgres_source_location(+ schema_name=schema_name,+ schema_metadata={+ "source_catalog": source_schema.source_catalog if source_schema else None,+ "source_schema": source_schema.source_schema if source_schema else None,+ "source_table_name": source_schema.source_table_name if source_schema else None,+ },+ default_schema=default_schema,+ )+++DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = "Direct query mode is currently supported only for Postgres, MySQL, Snowflake, Redshift, ClickHouse, MotherDuck, and Trino sources."++# Engines surfaced on a direct connection's `connection_metadata.engine` (duckdb backs direct Postgres).+DIRECT_CONNECTION_ENGINE_CHOICES = [+ "duckdb",+ "postgres",+ "mysql",+ "snowflake",+ "redshift",+ "clickhouse",+ "motherduck",+ "trino",+]+++def count_active_sources(team_id: int, source_type: str) -> int:+ return ExternalDataSource.objects.filter(team_id=team_id, source_type=source_type).exclude(deleted=True).count()+++def _refresh_name_substitutions(+ engine: DirectQueryEngine | None, *, source: ExternalDataSource, source_schemas: list[Any], team_id: int+) -> dict[str, str]:+ """Legacy-row name remapping applied before schema sync on refresh. The engine adapter's+ remapping wins when it has one (Postgres's bespoke dedup — an empty dict still counts as+ "handled" and suppresses the fallback); otherwise a multi-schema-capable SQL source with a+ blank namespace gets the generic migration. Neither applies to any other source."""+ if engine is not None:+ engine_subs = engine.refresh_name_substitutions(source=source, source_schemas=source_schemas, team_id=team_id)+ if engine_subs is not None:+ return engine_subs+ if source_namespace_is_blank(source) and is_multi_schema_capable_sql_source(source.source_type):+ return apply_sql_warehouse_refresh_migration(source=source, team_id=team_id)+ return {}diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/job_runs.py b/products/warehouse_sources/backend/presentation/views/external_data_source/job_runs.pynew file mode 100644index 000000000000..dff191deb4de--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/job_runs.py@@ -0,0 +1,218 @@+"""Serializers and endpoints for external data jobs."""++from __future__ import annotations++from typing import Any++from django.utils.cache import patch_cache_control++from dateutil import parser+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field+from rest_framework import serializers, status+from rest_framework.exceptions import ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import action++from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSource+from products.warehouse_sources.backend.facade.source_config import SourceConfigMapResponse+from products.warehouse_sources.backend.presentation.views.external_data_schema import (+ SimpleExternalDataSchemaSerializer,+)+from products.warehouse_sources.backend.presentation.views.public_source_configs import build_source_configs++from . import base+++class ExternalDataJobSerializers(serializers.ModelSerializer):+ schema = serializers.SerializerMethodField(read_only=True)+ status = serializers.SerializerMethodField(read_only=True)+ cdc_write_mode = serializers.SerializerMethodField(+ read_only=True,+ help_text=(+ "For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob "+ "rows produced per sync: `incremental_merge` (consolidated table) vs `scd2_append` "+ "(cdc-only history table). `null` for non-CDC syncs. Read from `schema_snapshot`."+ ),+ )+ billable = serializers.BooleanField(+ read_only=True,+ allow_null=True,+ help_text=(+ "Whether the rows synced by this job count toward billing. `false` for system-initiated "+ "runs the customer isn't charged for (e.g. rebuilding a table after an internal issue). "+ "`null` on legacy rows and means billable."+ ),+ )+ destination_ids = serializers.ListField(+ child=serializers.CharField(),+ read_only=True,+ help_text=(+ "Destinations this run delivered to, snapshotted when it started. Empty on runs that "+ "predate destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts "+ "the rows read from the source once, not once per destination."+ ),+ )++ class Meta:+ model = ExternalDataJob+ fields = [+ "id",+ "created_at",+ "created_by",+ "finished_at",+ "status",+ "schema",+ "rows_synced",+ "latest_error",+ "workflow_run_id",+ "cdc_write_mode",+ "billable",+ "destination_ids",+ ]+ read_only_fields = [+ "id",+ "created_at",+ "created_by",+ "finished_at",+ "status",+ "schema",+ "rows_synced",+ "latest_error",+ "workflow_run_id",+ "cdc_write_mode",+ "billable",+ "destination_ids",+ ]++ def get_cdc_write_mode(self, instance: ExternalDataJob) -> str | None:+ return (instance.schema_snapshot or {}).get("cdc_write_mode")++ @extend_schema_field(serializers.CharField())+ def get_status(self, instance: ExternalDataJob) -> str:+ if instance.status == ExternalDataJob.Status.BILLING_LIMIT_REACHED:+ return "Billing limits"++ if instance.status == ExternalDataJob.Status.BILLING_LIMIT_TOO_LOW:+ return "Billing limit too low"++ return instance.status++ @extend_schema_field(SimpleExternalDataSchemaSerializer)+ def get_schema(self, instance: ExternalDataJob) -> dict[str, Any]:+ return SimpleExternalDataSchemaSerializer(+ instance.schema, many=False, read_only=True, context=self.context+ ).data+++class ExternalDataSourceJobRunsMixin(base.ExternalDataSourceViewSetBase):+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="after",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="ISO timestamp — only return jobs created after this date.",+ ),+ OpenApiParameter(+ name="before",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="ISO timestamp — only return jobs created before this date.",+ ),+ OpenApiParameter(+ name="schemas",+ type={"type": "array", "items": {"type": "string"}},+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter jobs by table schema names.",+ ),+ ],+ responses=ExternalDataJobSerializers(many=True),+ )+ @action(methods=["GET"], detail=True, pagination_class=None)+ def jobs(self, request: Request, *arg: Any, **kwargs: Any):+ instance: ExternalDataSource = self.get_object()+ after = request.query_params.get("after", None)+ before = request.query_params.get("before", None)+ schemas = request.query_params.getlist("schemas")++ try:+ after_date = parser.parse(after) if after else None+ before_date = parser.parse(before) if before else None+ except (ValueError, OverflowError):+ raise ValidationError("after and before must be ISO 8601 timestamps.")++ # select_related joins the full ExternalDataSchema row; defer its large JSON/text+ # columns so the serializer only pulls the fields SimpleExternalDataSchemaSerializer+ # actually reads (sync_type_config + latest_error can each be sizeable).+ # Non-billable jobs are included on purpose: the UI shows them tagged so a sync the+ # customer wasn't charged for is still visible in the history.+ jobs = (+ instance.jobs.select_related("schema")+ .defer("schema__sync_type_config", "schema__latest_error")+ .order_by("-created_at")+ )++ if schemas:+ jobs = jobs.filter(schema__name__in=schemas)+ if after_date:+ jobs = jobs.filter(created_at__gt=after_date)+ if before_date:+ jobs = jobs.filter(created_at__lt=before_date)++ jobs = jobs[:50]++ return Response(+ status=status.HTTP_200_OK,+ data=ExternalDataJobSerializers(+ jobs, many=True, read_only=True, context=self.get_serializer_context()+ ).data,+ )++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description=(+ "Comma-separated source type(s) to return config for, e.g. 'Postgres' or "+ "'Postgres,Stripe'. Strongly recommended: the unfiltered response describes every "+ "supported source and is very large. Omit only to enumerate the available types."+ ),+ )+ ],+ responses={200: SourceConfigMapResponse},+ )+ @action(methods=["GET"], detail=False)+ def wizard(self, request: Request, *arg: Any, **kwargs: Any):+ # The documented-tables catalog is only consumed by the posthog.com docs build (via the+ # public endpoint) — skipping it here cuts ~40% off an already >1 MB response.+ configs = build_source_configs(include_tables=False)++ requested = request.query_params.get("source_type")+ if requested:+ requested_types = [t.strip() for t in requested.split(",") if t.strip()]+ unknown = [t for t in requested_types if t not in configs]+ if unknown:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Unknown source_type(s): {', '.join(sorted(unknown))}. "+ "Omit source_type to list every available type."+ },+ )+ configs = {st: config for st, config in configs.items() if st in requested_types}++ response = Response(status=status.HTTP_200_OK, data=configs)+ # The catalog is deploy-static and identical for every user (no team/user input), so let the+ # browser reuse it across navigations instead of re-downloading and re-parsing several hundred+ # KB on each visit to the new-source page. `private` because the route is auth-gated; a new+ # source ships at most once per deploy, so a short freshness window is safe.+ patch_cache_control(response, private=True, max_age=600)+ return responsediff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.py b/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.pynew file mode 100644index 000000000000..afee63f30774--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/oauth_accounts.py@@ -0,0 +1,165 @@+"""Serializers and endpoints for OAuth account selection."""++from __future__ import annotations++from typing import Any, cast++from django.core.cache import cache++from drf_spectacular.utils import OpenApiParameter, extend_schema+from rest_framework import serializers+from rest_framework.exceptions import ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import action+from posthog.models.integration import Integration+from posthog.permissions import TeamMemberAdminManagementPermission++from products.warehouse_sources.backend.facade.source_management import (+ IntegrationAccountListingError,+ OAuthMixin,+ filter_integration_accounts,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++from . import base, helpers+++class IntegrationAccountSerializer(serializers.Serializer):+ """A selectable account/resource exposed by an OAuth integration, in the shared shape every ad+ platform produces (see ``IntegrationAccount`` in the data-imports common module). One serializer+ and one frontend selector work across all platforms."""++ value = serializers.CharField(+ help_text="The identifier stored in the source config and used for API calls (numeric account id as a string, a site url, etc.)."+ )+ display_name = serializers.CharField(help_text="Primary human-readable label for the account.")+ is_primary = serializers.BooleanField(+ help_text="True when this account belongs to the connected user's own (primary) account context, rather than one they merely have access to. Sorted/marked first."+ )+ badges = serializers.ListField(+ child=serializers.CharField(),+ help_text="Short status chips for the account, e.g. ['Active'] or ['Pause'].",+ )+ group = serializers.CharField(+ allow_null=True,+ help_text="Optional grouping label for hierarchical platforms (e.g. the owning customer/manager name).",+ )+ secondary_text = serializers.CharField(+ allow_null=True,+ help_text="Extra identifier shown in parentheses and searchable, e.g. the alphanumeric account number.",+ )+++class IntegrationAccountsResponseSerializer(serializers.Serializer):+ accounts = IntegrationAccountSerializer(+ many=True,+ help_text="All accounts the connected integration can access.",+ )+++class AccountPickerManagementPermission(TeamMemberAdminManagementPermission):+ """Admin gate for the account picker, with a message the customer can act on.++ The base message names no next step. Free entry stays open on the account field, so a+ member who cannot list accounts can still finish the source by filling the account in.+ """++ message = (+ "You need admin access to this project to list the accounts this connection can reach. "+ "Ask an admin to finish the setup, or fill in the account yourself."+ )+++class ExternalDataSourceOAuthAccountsMixin(base.ExternalDataSourceViewSetBase):+ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="source_type",+ type=str,+ required=True,+ description="The data warehouse source type (e.g. 'BingAds', 'GoogleSearchConsole').",+ ),+ OpenApiParameter(+ name="integration_id",+ type=int,+ required=True,+ description="The OAuth integration id whose accounts should be listed.",+ ),+ OpenApiParameter(+ name="search",+ type=str,+ required=False,+ description="Optional case-insensitive filter over account name/value, for sources whose "+ "resource list is large (e.g. GitHub repositories).",+ ),+ ],+ responses={200: IntegrationAccountsResponseSerializer},+ )+ @action(methods=["GET"], detail=False, url_path="oauth_accounts")+ def oauth_accounts(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List the accounts/properties a connected OAuth integration exposes, in the shared+ IntegrationAccount shape. The logic lives in each source (via OAuthMixin.get_oauth_accounts);+ this endpoint just routes by source type, applies the optional search filter, and serializes."""+ source_type = request.query_params.get("source_type")+ integration_id = request.query_params.get("integration_id")+ search = request.query_params.get("search") or None+ if not source_type or not integration_id:+ raise ValidationError("source_type and integration_id are required")++ try:+ integration_id_int = int(integration_id)+ except ValueError:+ raise ValidationError("integration_id must be an integer")++ try:+ source = base.SourceRegistry.get_source(cast(ExternalDataSourceType, source_type))+ except ValueError:+ raise ValidationError(f"Unknown source type: {source_type}")++ if not isinstance(source, OAuthMixin):+ raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")++ # The integration id is caller-supplied and each source looks it up by (id, team_id) only, so+ # without this a same-team integration of a different provider would be accepted here and its+ # OAuth token handed to this source's provider. Pin it to the kind(s) the source's picker+ # declares before any of that runs.+ expected_kinds = helpers.get_oauth_integration_kinds(source.get_source_config.fields)+ if not expected_kinds:+ raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")+ if not Integration.objects.filter(+ id=integration_id_int, team_id=self.team_id, kind__in=expected_kinds+ ).exists():+ # One message for "gone" and "wrong kind" alike: from the UI both mean the picker is holding+ # a connection this source can't use, and neither tells the caller anything about ids it+ # isn't already allowed to see.+ raise ValidationError(+ f"No {source_type} connection was found for this integration. Please reconnect the integration."+ )++ cache_key = f"oauth_accounts/{self.team_id}/{source_type}/{integration_id_int}/{search or ''}"+ cached = cache.get(cache_key)+ if cached is not None:+ return Response(cached)++ try:+ accounts = source.get_oauth_accounts(integration_id_int, self.team_id, search=search)+ except NotImplementedError:+ # An OAuth source that hasn't implemented account listing yet (passes the isinstance check).+ raise ValidationError(f"Source type {source_type} does not support listing OAuth accounts")+ except IntegrationAccountListingError as e:+ # Actionable, customer-side failure (revoked/expired token, deleted integration, the provider+ # rejecting the credentials) — surface the message as a 400. Anything else (e.g. a bare+ # ValueError from an internal bug) stays uncaught and becomes a 500 so monitors see it.+ raise ValidationError(str(e))++ # Belt-and-suspenders: sources that support server-side search already return matching results;+ # this filters sources that returned a full list and ignored `search`.+ accounts = filter_integration_accounts(accounts, search)+ response_data = {"accounts": IntegrationAccountSerializer(accounts, many=True).data}+ # Don't cache an empty result: a transient provider hiccup that returns [] without raising would+ # otherwise poison the picker for 60s for every admin on the team.+ if accounts:+ cache.set(cache_key, response_data, 60)+ return Response(response_data)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.pynew file mode 100644index 000000000000..c33f81ab601b--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/schema_operations.py@@ -0,0 +1,662 @@+"""Serializers and endpoints for source schema operations."""++from __future__ import annotations++import uuid+from collections.abc import Callable, Iterable+from typing import Any, cast++from django.db import connection, transaction++from drf_spectacular.utils import extend_schema+from rest_framework import serializers, status+from rest_framework.exceptions import APIException, PermissionDenied, ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import action+from posthog.permissions import is_service_auth++from products.access_control.backend.facade.user_access_control import access_level_satisfied_for_resource+from products.data_warehouse.backend.facade.api import get_direct_query_engine, get_namespaced_resource_adapter+from products.warehouse_sources.backend.facade.models import (+ ExternalDataSchema,+ ExternalDataSource,+ auto_enable_new_schemas,+ sync_old_schemas_with_new_schemas,+)+from products.warehouse_sources.backend.facade.source_management import (+ AnySource,+ ClickHouseSource,+ Config,+ CustomSource,+ MySQLSource,+ PostgresSource,+ SQLSource,+ build_default_sync_settings,+ new_source_requires_ssl,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.presentation.views.external_data_schema import (+ ExternalDataSchemaSerializer,+ RowFiltersField,+)++from . import base, credential_store, helpers+++class RefreshSchemasResponseSerializer(serializers.Serializer):+ added = serializers.IntegerField(help_text="Number of schemas newly created from the source.")+ deleted = serializers.IntegerField(+ help_text="Number of schemas removed because they no longer exist on the source."+ )+ auto_enabled = serializers.IntegerField(+ help_text="Number of new schemas auto-enabled because the source has auto_sync_new_schemas on."+ )+ total_tables_seen = serializers.IntegerField(help_text="Total tables the source reported, before filtering.")+++class ExternalDataSourceBulkUpdateSchemaSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="Schema identifier to update.")+ should_sync = serializers.BooleanField(required=False, help_text="Whether the schema should be queryable/synced.")+ sync_type = serializers.ChoiceField(+ required=False,+ allow_null=True,+ choices=ExternalDataSchema.SyncType.choices,+ help_text="Requested sync mode for the schema (incremental, full_refresh, append, cdc, or xmin).",+ )+ incremental_field = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Incremental cursor field for incremental or append syncs.",+ )+ incremental_field_type = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Type of the incremental cursor field.",+ )+ sync_frequency = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Human-readable sync frequency value.",+ )+ sync_time_of_day = serializers.TimeField(+ required=False,+ allow_null=True,+ help_text="UTC anchor time for scheduled syncs.",+ )+ primary_key_columns = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ allow_null=True,+ help_text="Column names for primary key deduplication.",+ )+ cdc_table_mode = serializers.ChoiceField(+ required=False,+ allow_null=True,+ choices=["consolidated", "cdc_only", "both"],+ help_text="How CDC-backed tables should be exposed.",+ )+ enabled_columns = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ allow_null=True,+ allow_empty=True,+ help_text="Columns to sync. Null means sync all columns.",+ )+ row_filters = RowFiltersField(+ required=False,+ allow_null=True,+ help_text="Row-filter predicates ANDed onto the source query. Null/empty means sync all rows.",+ )+ apply_sync_defaults = serializers.BooleanField(+ required=False,+ help_text=(+ "When true and the schema has no sync method configured yet (and this update does not set "+ "one), discover the table on the source and fill in default sync settings: incremental sync "+ "with an auto-selected tracking column where supported, otherwise append, otherwise full "+ "refresh. Ignored for schemas that already have a sync method."+ ),+ )+++class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):+ schemas = ExternalDataSourceBulkUpdateSchemaSerializer(+ many=True,+ allow_empty=False,+ help_text="Schema updates to apply in a single batch.",+ )++ # The endpoint is a PATCH, so the schema generator marks every field optional. The body is a+ # batch command that always needs `schemas`, and the generated types and MCP tool must say so.+ @property+ def partial(self) -> bool:+ return False++ @partial.setter+ def partial(self, _value: bool) -> None:+ pass+++def _validation_error_message(error: ValidationError) -> str:+ # DRF normalizes ValidationError.detail to a list or dict (never a bare string).+ detail = error.detail+ if isinstance(detail, dict):+ return " ".join(f"{field}: {value}" for field, value in detail.items())+ return " ".join(str(item) for item in detail)+++class BulkSchemaSaveError(APIException):+ default_code = "bulk_schema_save_failed"++ def __init__(self, failures: dict[str, tuple[str, str]], *, only_validation_errors: bool) -> None:+ # Pure input problems are the caller's to fix (400). A database/infra error is ours and is+ # retryable (503); treat a mix as a server problem so it surfaces as retryable.+ self.status_code = (+ status.HTTP_400_BAD_REQUEST if only_validation_errors else status.HTTP_503_SERVICE_UNAVAILABLE+ )+ reasons = "; ".join(f"{name} ({reason})" for name, reason in failures.values())+ super().__init__(+ detail=(+ f"These schemas in the batch could not be saved: {reasons}. "+ "Any other schemas in the batch were saved successfully — retry the ones listed here."+ )+ )+++class ExternalDataSourceSchemaOperationsMixin(base.ExternalDataSourceViewSetBase):+ def _assert_can_write_schemas(self, schemas: Iterable[ExternalDataSchema]) -> None:+ """Per-table gate for source-level endpoints that write or sync schemas.++ Editor on the source isn't enough: a table can be locked below that, and these endpoints+ never resolve a schema through DRF's object permissions, so nothing else checks it. Each+ schema resolves like the schema viewset's permission: through its table, which falls back+ to the source via RESOURCE_FALLBACK_MAP.+ """+ # Service credentials are synthetic users UserAccessControl can't evaluate; they're gated by+ # API scope + project membership. Mirror AccessControlPermission.+ if is_service_auth(self.request):+ return+ uac = self.user_access_control+ for schema in schemas:+ level = uac.get_user_access_level(schema.table or schema.source)+ if level is None or not access_level_satisfied_for_resource("warehouse_table", level, "editor"):+ raise PermissionDenied("You do not have editor access to every table in this source.")++ @action(methods=["POST"], detail=True)+ @extend_schema(responses=RefreshSchemasResponseSerializer)+ def refresh_schemas(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Fetch current schema/table list from the source and create any new ExternalDataSchema rows (no data sync)."""+ instance: ExternalDataSource = self.get_object()+ base.logger.debug(+ "refresh_schemas called",+ source_id=str(instance.id),+ team_id=self.team_id,+ source_type=instance.source_type,+ )+ if not instance.job_inputs:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Source has no configuration."},+ )+ source: AnySource | None = None+ try:+ source_type = ExternalDataSourceType(instance.source_type)+ source = base.SourceRegistry.get_source(source_type)+ config = source.parse_config(instance.job_inputs)+ # Explicit user action — bypass any cached schema discovery so newly added+ # upstream resources (e.g. Slack channels) appear immediately.+ schemas = source.get_schemas(+ config, self.team_id, force_refresh=True, api_version=source.resolve_api_version(instance.api_version)+ )+ connection_metadata = (+ helpers.get_direct_connection_metadata(+ source_impl=source,+ source_config=config,+ team_id=self.team_id,+ source_model=instance,+ fallback=instance.connection_metadata,+ )+ if instance.is_direct_query+ else instance.connection_metadata+ )+ schema_names = {s.name: s.label for s in schemas}+ base.logger.info(+ "refresh_schemas fetched from source",+ source_id=str(instance.id),+ schema_count=len(schema_names),+ schema_names=schema_names,+ )+ except Exception as e:+ error_message, is_expected_source_error = helpers._classify_refresh_schemas_error(source, e)+ base.logger.exception(+ "Could not fetch schemas from source",+ exc_info=e,+ source_id=str(instance.id),+ team_id=self.team_id,+ source_type=instance.source_type,+ error_type=type(e).__name__,+ is_expected_source_error=is_expected_source_error,+ )+ if not is_expected_source_error:+ base.capture_exception(+ e,+ {+ "source_id": str(instance.id),+ "source_type": instance.source_type,+ "team_id": self.team_id,+ "refresh_schemas": True,+ },+ )+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": error_message},+ )++ descriptions = {s.name: s.description for s in schemas}+ with transaction.atomic():+ ExternalDataSource._base_manager.filter(pk=instance.pk).select_for_update().get()+ if instance.is_direct_query and connection_metadata != instance.connection_metadata:+ instance.connection_metadata = connection_metadata+ instance.save(update_fields=["connection_metadata", "updated_at"])+ # Migrate/dedupe legacy rows before sync_old_schemas; non-Postgres only once namespace cleared.+ engine = get_direct_query_engine(instance.direct_engine)+ name_substitutions = helpers._refresh_name_substitutions(+ engine, source=instance, source_schemas=schemas, team_id=self.team_id+ )++ if name_substitutions:+ schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}+ descriptions = {+ name_substitutions.get(name, name): description for name, description in descriptions.items()+ }+ # Namespaced-resource sources (GitHub) keep the legacy resource's rows bare alongside+ # qualified rows for the others, so bare↔qualified tail matching would wrongly collapse+ # them; match names exactly and seed per-resource location metadata on new rows.+ namespaced_adapter = get_namespaced_resource_adapter(instance.source_type)+ sync_result = sync_old_schemas_with_new_schemas(+ schema_names,+ source_id=str(instance.id),+ team_id=self.team_id,+ descriptions=descriptions,+ strict_name_match=namespaced_adapter is not None and namespaced_adapter.uses_strict_schema_name_match,+ schema_metadata_by_name=namespaced_adapter.schema_metadata_by_name(schemas)+ if namespaced_adapter is not None+ else None,+ )+ # Mutable local: engine reconciliation below may extend the deleted set.+ schemas_deleted = sync_result.deleted++ if engine is not None:+ reconciled_deleted_schemas = engine.reconcile_schemas(+ source=instance, source_schemas=schemas, team_id=self.team_id+ )+ if reconciled_deleted_schemas:+ schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})+ elif isinstance(source, (SQLSource, ClickHouseSource)) and source.supports_column_selection:+ # ClickHouse isn't a SQLSource but exposes the same column-selection+ # capability and reconcile hook, so it reuses this path.+ source.reconcile_schema_metadata(source=instance, source_schemas=schemas, team_id=self.team_id)++ # Outside the atomic block: schedule creation talks to Temporal, which must not run under+ # the source row lock or against rows that could still roll back. `sync_result.created` holds+ # post-substitution stored names, so remap the discovered names to match.+ auto_enabled_names: list[str] = []+ if sync_result.created:+ source_schemas_by_name = {name_substitutions.get(s.name, s.name): s for s in schemas}+ auto_enabled_names = auto_enable_new_schemas(instance, sync_result.created, source_schemas_by_name)++ base.logger.debug(+ "refresh_schemas completed",+ source_id=str(instance.id),+ team_id=self.team_id,+ added=len(sync_result.created),+ deleted=len(schemas_deleted),+ auto_enabled=len(auto_enabled_names),+ total_tables_seen=len(schemas),+ )+ return Response(+ status=status.HTTP_200_OK,+ data=RefreshSchemasResponseSerializer(+ {+ "added": len(sync_result.created),+ "deleted": len(schemas_deleted),+ "auto_enabled": len(auto_enabled_names),+ "total_tables_seen": len(schemas),+ }+ ).data,+ )++ @extend_schema(request=credential_store.DatabaseSchemaRequestSerializer)+ @action(methods=["POST"], detail=False)+ def database_schema(self, request: Request, *arg: Any, **kwargs: Any):+ source_type = request.data.get("source_type", None)++ if source_type is None:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Missing required parameter: source_type"},+ )++ secret_ref_response = credential_store._unresolved_secret_ref_response(request.data)+ if secret_ref_response is not None:+ return secret_ref_response++ try:+ source_type_model = ExternalDataSourceType(source_type)+ except ValueError:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Unknown source_type '{source_type}'"},+ )+ source = base.SourceRegistry.get_source(source_type_model)+ is_valid, errors = source.validate_config(request.data)+ if not is_valid:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid source config: {', '.join(errors)}"},+ )+ source_config: Config = source.parse_config(request.data)++ access_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)+ try:+ if isinstance(source, (PostgresSource, MySQLSource)):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config),+ self.team_id,+ access_method,+ require_ssl=new_source_requires_ssl(source_config),+ )+ elif isinstance(source, CustomSource):+ # Schema discovery for an as-yet-uncreated source: an integration-backed manifest may only use+ # an unbound integration owned by the requester, or the probe could send another source's token+ # to the submitted host.+ credentials_valid, credentials_error = source.validate_credentials(+ source_config, self.team_id, owner_user_id=self.request.user.id+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ except Exception as e:+ credentials_valid, credentials_error = helpers._credentials_validation_failed(source, self.team_id, e)+ if not credentials_valid:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": credentials_error or helpers.INVALID_CREDENTIALS_FALLBACK_MESSAGE},+ )++ try:+ schemas = source.get_schemas(source_config, self.team_id)+ except NotImplementedError:+ # Source doesn't implement schema discovery (e.g. an unreleased source), so there are+ # no tables to list — a caller mistake, not a server error worth capturing. Mirrors `setup`.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers._source_unavailable_message(source_type)},+ )+ except Exception as e:+ error_message, is_expected_source_error = helpers._classify_refresh_schemas_error(source, e)+ if not is_expected_source_error:+ base.capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": error_message},+ )++ # Best-effort per-endpoint scope probe — transient failure falls back to "available".+ try:+ endpoint_permissions = source.get_endpoint_permissions(+ source_config, self.team_id, [schema.name for schema in schemas]+ )+ except Exception as e:+ base.capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ endpoint_permissions = {schema.name: None for schema in schemas}++ # Cache the CDC flag once: in non-DEBUG environments this calls posthoganalytics.feature_enabled,+ # which makes a network round-trip per call. With large schema lists (e.g. Slack workspaces with+ # thousands of channels) the per-iteration call inflated the response loop past the 120s gateway.+ cdc_enabled = base.is_cdc_enabled_for_team(self.team)+ # xmin is gated at the source-type level by the source's capability flag so it never+ # leaks to another SQL source.+ xmin_capable = source.supports_xmin+ data = [+ {+ "table": schema.name,+ "label": schema.label,+ "should_sync": False,+ "incremental_fields": schema.incremental_fields,+ "incremental_available": schema.supports_incremental,+ "append_available": schema.supports_append,+ "cdc_available": schema.supports_cdc if cdc_enabled else None,+ "xmin_available": schema.supports_xmin if xmin_capable else None,+ "incremental_field": schema.incremental_fields[0]["field"]+ if len(schema.incremental_fields) > 0 and len(schema.incremental_fields[0]["field"]) > 0+ else None,+ "sync_type": None,+ "rows": schema.row_count,+ "supports_webhooks": schema.supports_webhooks,+ "webhook_only": schema.webhook_only,+ "description": schema.description,+ "should_sync_default": schema.should_sync_default,+ "available_columns": [+ {"field": col_name, "label": col_name, "type": col_type, "nullable": nullable}+ for col_name, col_type, nullable in schema.columns+ ],+ "detected_primary_keys": schema.detected_primary_keys,+ "permission_error": endpoint_permissions.get(schema.name),+ "rls_warning": schema.rls_warning,+ }+ for schema in schemas+ ]+ return Response(status=status.HTTP_200_OK, data=data)++ def _fill_default_sync_settings(+ self,+ source: ExternalDataSource,+ schema_updates: list[dict[str, Any]],+ source_schemas_by_id: dict[uuid.UUID, ExternalDataSchema],+ # nosemgrep: tuple-return-prefer-dataclass -- grandfathered backlog+ ) -> tuple[dict[str, tuple[str, str]], set[str]]:+ """Fill default sync settings into bulk-update items that ask for them.++ Items with ``apply_sync_defaults`` targeting a schema that has no sync method yet (and+ whose update doesn't set one) get their sync settings discovered from the source — one+ discovery call for the whole batch. Returns per-schema failures (dropped tables,+ webhook-only tables, discovery errors) for the caller to skip and report, plus the ids+ of the schemas whose settings were filled in.+ """+ needing_defaults = [+ schema_update+ for schema_update in schema_updates+ if schema_update.get("apply_sync_defaults")+ and schema_update.get("sync_type") is None+ and source_schemas_by_id[schema_update["id"]].sync_type is None+ ]+ # Direct-query sources have no sync method to configure — enabling is just should_sync.+ if not needing_defaults or not source.supports_scheduled_sync:+ return {}, set()++ failures: dict[str, tuple[str, str]] = {}+ names = [source_schemas_by_id[schema_update["id"]].name for schema_update in needing_defaults]+ source_impl: AnySource | None = None+ try:+ source_impl = base.SourceRegistry.get_source(ExternalDataSourceType(source.source_type))+ config = source_impl.parse_config(source.job_inputs)+ discovered = source_impl.get_schemas(+ config, self.team_id, names=names, api_version=source_impl.resolve_api_version(source.api_version)+ )+ except Exception as e:+ # Discovery connects to the customer's source, so an expected user/upstream failure+ # (bad credentials, unreachable host) is theirs to fix and is already reported back to+ # them below — don't capture it as error-tracking noise. Mirrors `refresh_schemas`.+ _, is_expected_source_error = helpers._classify_refresh_schemas_error(source_impl, e)+ if not is_expected_source_error:+ base.capture_exception(e)+ reason = "could not read the source to pick default sync settings; check the source credentials"+ for schema_update in needing_defaults:+ schema = source_schemas_by_id[schema_update["id"]]+ failures[str(schema.id)] = (schema.name, reason)+ return failures, set()++ # Not every source honors the `names` filter, so match by name instead of order.+ discovered_by_name = {discovered_schema.name: discovered_schema for discovered_schema in discovered}+ defaulted_schema_ids: set[str] = set()+ for schema_update in needing_defaults:+ schema = source_schemas_by_id[schema_update["id"]]+ discovered_schema = discovered_by_name.get(schema.name)+ if discovered_schema is None:+ failures[str(schema.id)] = (+ schema.name,+ "not found on the source; pull new schemas to refresh the table list",+ )+ continue+ if discovered_schema.webhook_only:+ failures[str(schema.id)] = (+ schema.name,+ "can only be synced via webhooks; set up the webhook sync method instead",+ )+ continue+ for key, value in build_default_sync_settings(discovered_schema).items():+ # A caller-sent value wins; None (missing or explicit null) means "not set".+ if schema_update.get(key) is None:+ schema_update[key] = value+ defaulted_schema_ids.add(str(schema.id))+ return failures, defaulted_schema_ids++ @extend_schema(+ request=ExternalDataSourceBulkUpdateSchemasSerializer,+ responses={200: ExternalDataSchemaSerializer(many=True)},+ )+ # The list-shaped response makes the generator add the viewset's search and paging params.+ @action(methods=["PATCH"], detail=True, pagination_class=None, filter_backends=[])+ def bulk_update_schemas(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ source = self.get_object()+ serializer = ExternalDataSourceBulkUpdateSchemasSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ schema_updates: list[dict[str, Any]] = serializer.validated_data["schemas"]+ schema_ids = [schema_update["id"] for schema_update in schema_updates]++ if len(set(schema_ids)) != len(schema_ids):+ raise ValidationError("Schema updates must contain unique ids")++ source_schemas = ExternalDataSchema.objects.filter(+ team_id=self.team_id,+ source_id=source.id,+ id__in=schema_ids,+ ).select_related("source", "table__credential", "table__external_data_source")+ source_schemas_by_id = {schema.id: schema for schema in source_schemas}++ if len(source_schemas_by_id) != len(schema_ids):+ raise ValidationError("One or more schemas could not be found for this source")++ # Reject up front rather than per-schema, so a batch touching a locked table writes nothing.+ self._assert_can_write_schemas(source_schemas_by_id.values())++ # Items that ask for sync defaults on a not-yet-configured schema get them discovered and+ # filled in up front. Tables that can't get defaults (dropped from the source, webhook-only)+ # fail individually and are skipped below, without blocking the rest of the batch.+ failed_schemas, defaulted_schema_ids = self._fill_default_sync_settings(+ source, schema_updates, source_schemas_by_id+ )+ only_validation_errors = True++ serializer_context = self.get_serializer_context()+ updated_schemas: list[ExternalDataSchema] = []+ # Each deferred action is paired with its schema so a post-commit failure can be attributed.+ post_commit_actions: list[tuple[ExternalDataSchema, Callable[[], None]]] = []++ # Validate every payload before writing anything, so a malformed request is rejected up+ # front. Some checks only run inside the serializer's update() (during save() below), so+ # this catches the common input errors but not all of them — the save loop handles the rest.+ prepared: list[tuple[ExternalDataSchema, ExternalDataSchemaSerializer, list[Callable[[], None]]]] = []+ for schema_update in schema_updates:+ schema_id = schema_update["id"]+ schema = source_schemas_by_id[schema_id]+ if str(schema.id) in failed_schemas:+ continue+ schema_payload = {+ key: value for key, value in schema_update.items() if key not in ("id", "apply_sync_defaults")+ }++ schema_post_commit_actions: list[Callable[[], None]] = []+ schema_serializer = ExternalDataSchemaSerializer(+ schema,+ data=schema_payload,+ partial=True,+ context={**serializer_context, "post_commit_actions": schema_post_commit_actions},+ )+ schema_serializer.is_valid(raise_exception=True)+ if str(schema.id) in defaulted_schema_ids:+ # Defaults discovery already confirmed these tables aren't webhook-only; seed the+ # cache so the warm step below doesn't re-probe the source once per schema.+ schema_serializer.seed_webhook_only_check(False)+ # Do the webhook-only source-discovery call (e.g. Google Ads token refresh + field query)+ # here, before the per-schema transaction below. Running it inside update()'s transaction+ # held the DB connection idle-in-transaction long enough for the server to close it.+ # update() reads the cached result, so it still validates and fails per-schema.+ schema_serializer.warm_webhook_only_check(schema)+ prepared.append((schema, schema_serializer, schema_post_commit_actions))++ # Commit each schema in its own transaction. A single atomic block around the whole batch+ # meant one schema's failure rolled back every schema and failed the request, so the user+ # got nothing applied. Isolating per schema keeps the ones that saved committed, attempts+ # every schema so a single bad one can't block the rest, and reports the failures together.+ for schema, schema_serializer, schema_post_commit_actions in prepared:+ try:+ with transaction.atomic():+ updated_schemas.append(schema_serializer.save())+ except Exception as e:+ if isinstance(e, ValidationError):+ reason = _validation_error_message(e)+ base.logger.warning(+ "bulk_update_schemas validation error during save",+ source_id=str(source.id),+ schema_id=str(schema.id),+ )+ else:+ only_validation_errors = False+ reason = "a database error occurred while saving"+ base.capture_exception(e)+ base.logger.exception(+ "bulk_update_schemas failed to persist schema",+ source_id=str(source.id),+ schema_id=str(schema.id),+ )+ failed_schemas[str(schema.id)] = (schema.name, reason)+ # A dropped connection leaves Django holding a dead handle; reset it so the next+ # schema reconnects instead of failing on the same broken connection.+ if not connection.is_usable():+ connection.close()+ continue++ # Only run a schema's Temporal side effects once its own row is committed.+ post_commit_actions.extend((schema, action) for action in schema_post_commit_actions)++ post_commit_error: Exception | None = None+ for action_schema, post_commit_action in post_commit_actions:+ try:+ post_commit_action()+ except Exception as e:+ # The row is already committed but its schedule still runs the old cadence. Capture ++ # log every failure (with the schema id) so the drift is visible, and remember it so+ # the request fails below — the caller must know the batch did not fully apply.+ post_commit_error = e+ base.capture_exception(e)+ base.logger.warning(+ "bulk_update_schemas saved the schema but its Temporal schedule update failed",+ source_id=str(source.id),+ schema_id=str(action_schema.id),+ exc_info=e,+ )++ # Report save failures first so a schedule-update failure can't mask which schemas didn't+ # save, then fail the request on the schedule-update failure.+ if failed_schemas:+ raise BulkSchemaSaveError(failed_schemas, only_validation_errors=only_validation_errors)+ if post_commit_error is not None:+ raise post_commit_error++ return Response(+ ExternalDataSchemaSerializer(updated_schemas, many=True, context=serializer_context).data,+ status=status.HTTP_200_OK,+ )diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.pynew file mode 100644index 000000000000..daf704e62a0b--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py@@ -0,0 +1,2243 @@+"""Serializers and endpoints for source setup."""++from __future__ import annotations++import uuid+from datetime import UTC, datetime, timedelta+from typing import Any, cast++from django.core.exceptions import ValidationError as DjangoValidationError+from django.db import transaction+from django.db.models import Q+from django.utils import timezone++import temporalio+from drf_spectacular.utils import extend_schema, extend_schema_field+from openai import APIConnectionError+from rest_framework import serializers, status+from rest_framework.exceptions import ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.hogql.direct_sql.capability import direct_capable_source_types++from posthog.api.utils import action+from posthog.event_usage import EventSource, get_event_source, is_wizard_self_driving_program, report_user_action+from posthog.exceptions_capture import capture_exception+from posthog.models.user import User++from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin+from products.data_modeling.backend.facade.models import DataWarehouseManagedViewSet+from products.data_warehouse.backend.facade.api import (+ apply_on_schema_clear as apply_sql_warehouse_schema_clear_migration,+ delete_webhook_and_hog_function,+ detect_schema_clear_transition as detect_sql_schema_clear_transition,+ get_direct_query_engine,+ get_namespaced_resource_adapter,+ is_any_external_data_schema_paused,+ is_custom_source_ai_builder_enabled_for_team,+)+from products.warehouse_sources.backend.facade.api import validate_source_prefix+from products.warehouse_sources.backend.facade.models import (+ DataWarehouseTable,+ ExternalDataJob,+ ExternalDataSchema,+ ExternalDataSource,+ PendingSourceCredential,+ sync_old_schemas_with_new_schemas,+)+from products.warehouse_sources.backend.facade.source_management import (+ PREVIEW_DEFAULT_ROWS,+ PREVIEW_MAX_ROWS,+ AnySource,+ CDCSourceAdapter,+ Config,+ CustomSource,+ CustomSourceConfig,+ DocsFetchError,+ MySQLSource,+ PostgresSource,+ RowFilterValidationError,+ SourceRegistry,+ SourceSchema,+ WebhookSource,+ build_default_schemas,+ draft_manifest_sync,+ fetch_docs_text,+ filter_dwh_columns_by_enabled_columns,+ get_cdc_adapter,+ new_source_requires_ssl,+ sql_schema_metadata,+ validate_and_coerce_row_filters,+)+from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType+from products.warehouse_sources.backend.presentation.views.destination_links import set_source_destinations+from products.warehouse_sources.backend.presentation.views.external_data_schema import (+ ExternalDataSchemaListSerializer,+ ExternalDataSchemaSerializer,+ source_supports_column_selection,+ unsupported_row_filter_reason,+)+from products.warehouse_sources.backend.presentation.views.source_api_versions import (+ ExternalDataSourceApiVersionDeprecationSerializer,+ api_version_deprecation_payload,+)++from . import base, connection_options, credential_store, helpers, webhook_setup+++class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializers.ModelSerializer):+ account_id = serializers.CharField(write_only=True)+ client_secret = serializers.CharField(write_only=True)+ last_run_at = serializers.SerializerMethodField(read_only=True)+ created_by = serializers.SerializerMethodField(read_only=True)+ latest_error = serializers.SerializerMethodField(read_only=True)+ status = serializers.SerializerMethodField(read_only=True)+ schemas = serializers.SerializerMethodField(read_only=True)+ engine = serializers.ChoiceField(+ source="connection_metadata.engine",+ read_only=True,+ allow_null=True,+ required=False,+ choices=helpers.DIRECT_CONNECTION_ENGINE_CHOICES,+ help_text="Backend engine detected for the direct connection.",+ )+ revenue_analytics_config = connection_options.ExternalDataSourceRevenueAnalyticsConfigSerializer(+ source="revenue_analytics_config_safe", read_only=True+ )+ access_method = serializers.ChoiceField(choices=ExternalDataSource.AccessMethod.choices, read_only=True)+ supports_webhooks = serializers.SerializerMethodField(read_only=True)+ supports_column_selection = serializers.SerializerMethodField(+ read_only=True,+ help_text="Whether this source supports per-column sync selection via `enabled_columns`.",+ )+ # Optional on both create and update. On create, missing values default to `api`+ # in the viewset to preserve backward compatibility with direct API callers that+ # predate this field; the in-app UI and MCP tool always send it explicitly.+ # `update` strips it to make the field write-once.+ # `allow_null=True` because historical rows (created before migration 0049) have+ # `created_via=NULL`, and the settings page spreads the GET payload back into PATCH.+ created_via = serializers.ChoiceField(+ choices=ExternalDataSource.CreatedVia.choices,+ required=False,+ allow_null=True,+ help_text=(+ "How this source was created. Defaults to `api` on create when omitted. "+ "`web` for the in-app UI, `api` for direct API callers, `mcp` for agent/MCP tool calls, "+ "`wizard` for the setup wizard and `self_driving` for the PostHog Desktop app "+ "(both derived server-side from the caller's user agent). "+ "Ignored on update."+ ),+ )+ direct_query_enabled = serializers.BooleanField(+ required=False,+ help_text=(+ "Whether this synced source is also live-queryable via direct connection. "+ "Defaults to false for new sources; ignored for pure direct-query sources."+ ),+ )+ auto_sync_new_schemas = serializers.BooleanField(+ required=False,+ help_text=(+ "Automatically enable syncing for schemas discovered on this source after creation, "+ "on both the scheduled discovery pass and manual schema refreshes. Defaults to false. "+ "Not supported for direct-query sources."+ ),+ )+ auto_sync_schema_patterns = serializers.ListField(+ child=serializers.CharField(+ max_length=250,+ allow_blank=False,+ help_text="An fnmatch-style glob pattern, e.g. `raw_*`.",+ ),+ required=False,+ allow_null=True,+ max_length=100,+ help_text=(+ "Optional fnmatch-style globs (`*` and `?` wildcards) restricting which newly discovered "+ "schema names auto-sync, matched case-insensitively against both the qualified and bare "+ "table name. Null or empty means every new schema qualifies. Only used when "+ "`auto_sync_new_schemas` is true."+ ),+ )+ api_version = serializers.CharField(+ read_only=True,+ allow_null=True,+ help_text=(+ "Vendor API version this source is pinned to (an opaque vendor label, e.g. a Stripe "+ "date version). Null resolves to the source type's default version at sync time."+ ),+ )+ api_version_deprecation = serializers.SerializerMethodField(+ read_only=True,+ help_text=(+ "Set when the vendor has deprecated the API version this source is pinned to; "+ "null otherwise. Drives the in-product deprecation warning."+ ),+ )++ class Meta:+ model = ExternalDataSource+ fields = [+ "id",+ "created_at",+ "created_by",+ "created_via",+ "status",+ "client_secret",+ "account_id",+ "source_type",+ "latest_error",+ "prefix",+ "description",+ "access_method",+ "direct_query_enabled",+ "auto_sync_new_schemas",+ "auto_sync_schema_patterns",+ "engine",+ "last_run_at",+ "schemas",+ "job_inputs",+ "revenue_analytics_config",+ "user_access_level",+ "supports_webhooks",+ "supports_column_selection",+ "api_version",+ "api_version_deprecation",+ ]+ read_only_fields = [+ "id",+ "created_by",+ "created_at",+ "status",+ "source_type",+ "latest_error",+ "last_run_at",+ "schemas",+ "engine",+ "revenue_analytics_config",+ "user_access_level",+ "access_method",+ "supports_webhooks",+ "supports_column_selection",+ "api_version",+ "api_version_deprecation",+ ]++ def to_representation(self, instance):+ representation = super().to_representation(instance)++ job_inputs = representation.get("job_inputs", {})+ if not isinstance(job_inputs, dict):+ return representation++ # Derive allowed keys dynamically from source config field definitions+ try:+ source_type_model = ExternalDataSourceType(instance.source_type)+ source = SourceRegistry.get_source(source_type_model)+ split = helpers.get_nonsensitive_and_sensitive_field_names(source.get_source_config.fields)+ # CDC fields aren't form fields but are non-secret operational config the UI needs.+ nonsensitive = split.nonsensitive | helpers._CDC_EXPOSED_JOB_INPUT_KEYS+ except (ValueError, KeyError):+ representation["job_inputs"] = {}+ return representation++ # Normalize SSH tunnel legacy format before stripping+ if "ssh_tunnel" in job_inputs and isinstance(job_inputs["ssh_tunnel"], dict):+ tunnel = job_inputs["ssh_tunnel"]+ # Normalize 'auth_type' (legacy from migration 0807) -> 'auth'+ if "auth_type" in tunnel and "auth" not in tunnel:+ tunnel["auth"] = tunnel.pop("auth_type")+ if isinstance(tunnel.get("auth"), dict):+ auth = tunnel["auth"]+ # Normalize 'type' (legacy) -> 'selection'+ if "type" in auth and "selection" not in auth:+ auth["selection"] = auth.pop("type")+ # Backfill require_tls default for sources created before the toggle existed+ if "require_tls" not in tunnel:+ tunnel["require_tls"] = {"enabled": True}++ stripped = helpers.strip_sensitive_from_dict(job_inputs, nonsensitive, split.sensitive)+ declared = helpers.get_declared_field_names(source.get_source_config.fields)+ representation["job_inputs"] = helpers.restore_declared_field_names(stripped, declared.hyphenated)+ return representation++ def get_last_run_at(self, instance: ExternalDataSource) -> str | None:+ latest_completed_run = instance.ordered_jobs[0] if instance.ordered_jobs else None # type: ignore++ return latest_completed_run.created_at.isoformat() if latest_completed_run else None++ def get_created_by(self, instance: ExternalDataSource) -> str | None:+ return instance.created_by.email if instance.created_by else None++ def get_supports_webhooks(self, instance: ExternalDataSource) -> bool:+ try:+ source = SourceRegistry.get_source(ExternalDataSourceType(instance.source_type))+ return isinstance(source, WebhookSource)+ except Exception as e:+ capture_exception(e)+ return False++ def get_supports_column_selection(self, instance: ExternalDataSource) -> bool:+ return source_supports_column_selection(instance.source_type)++ @extend_schema_field(ExternalDataSourceApiVersionDeprecationSerializer(allow_null=True))+ def get_api_version_deprecation(self, instance: ExternalDataSource) -> dict[str, Any] | None:+ return api_version_deprecation_payload(instance.source_type, instance.api_version)++ def _prefetched_schemas(self, instance: ExternalDataSource) -> list[ExternalDataSchema] | None:+ prefetched = getattr(instance, "_prefetched_objects_cache", {}).get("schemas")+ if prefetched is None:+ return None+ return [schema for schema in prefetched if not schema.deleted]++ def _active_schemas(self, instance: ExternalDataSource) -> list[ExternalDataSchema]:+ """Schemas that are syncing or carry an error — derived in Python from the single `schemas`+ prefetch rather than a second DB scan of the same (potentially huge) table."""+ prefetched = self._prefetched_schemas(instance)+ if prefetched is not None:+ return [schema for schema in prefetched if schema.should_sync or schema.latest_error is not None]+ return list(instance.schemas.exclude(deleted=True).filter(Q(should_sync=True) | Q(latest_error__isnull=False)))++ def get_status(self, instance: ExternalDataSource) -> str:+ active_schemas: list[ExternalDataSchema] = self._active_schemas(instance)+ # Negative statuses should ignore schemas the user has disabled — those can linger in+ # active_schemas via the latest_error prefetch but shouldn't drag the source into a failed state.+ syncing_schemas = [schema for schema in active_schemas if schema.should_sync]+ any_failures = any(schema.status == ExternalDataSchema.Status.FAILED for schema in syncing_schemas)+ any_billing_limits_reached = any(+ schema.status == ExternalDataSchema.Status.BILLING_LIMIT_REACHED for schema in syncing_schemas+ )+ any_billing_limits_too_low = any(+ schema.status == ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW for schema in syncing_schemas+ )+ any_paused = any(schema.status == ExternalDataSchema.Status.PAUSED for schema in active_schemas)+ any_running = any(schema.status == ExternalDataSchema.Status.RUNNING for schema in active_schemas)+ any_completed = any(schema.status == ExternalDataSchema.Status.COMPLETED for schema in active_schemas)++ if any_failures:+ return ExternalDataSchema.Status.FAILED+ elif any_billing_limits_reached:+ return "Billing limits"+ elif any_billing_limits_too_low:+ return "Billing limits too low"+ elif any_paused:+ return ExternalDataSchema.Status.PAUSED+ elif any_running:+ return ExternalDataSchema.Status.RUNNING+ elif any_completed:+ return ExternalDataSchema.Status.COMPLETED+ else:+ # Fallback during migration phase of going from source -> schema as the source of truth for syncs+ return instance.status++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_latest_error(self, instance: ExternalDataSource):+ prefetched_schemas = self._prefetched_schemas(instance)+ if prefetched_schemas is not None:+ schema_with_error = next(+ (schema for schema in prefetched_schemas if schema.latest_error is not None),+ None,+ )+ else:+ schema_with_error = instance.schemas.filter(latest_error__isnull=False).first()+ return schema_with_error.latest_error if schema_with_error else None++ @extend_schema_field(serializers.ListField(child=serializers.DictField()))+ def get_schemas(self, instance: ExternalDataSource):+ prefetched_schemas = getattr(instance, "_prefetched_objects_cache", {}).get("schemas")+ if prefetched_schemas is not None:+ schemas = [schema for schema in prefetched_schemas if not schema.deleted]+ else:+ schemas = list(instance.schemas.exclude(deleted=True).order_by("name"))+ # The source list embeds every schema of every source; large projects have tens of thousands.+ # The list UI only reads a handful of per-schema fields, so serialize the trimmed shape there+ # and reserve the full serializer for single-source reads.+ if self.context.get("schemas_list_only"):+ return ExternalDataSchemaListSerializer(schemas, many=True, read_only=True, context=self.context).data+ return ExternalDataSchemaSerializer(schemas, many=True, read_only=True, context=self.context).data++ def update(self, instance: ExternalDataSource, validated_data: Any) -> Any:+ request = self.context.get("request")+ requested_access_method = request.data.get("access_method") if request is not None else None+ if requested_access_method is not None and requested_access_method != instance.access_method:+ raise ValidationError("Access method cannot be changed. Create a new source instead.")++ validated_data.pop("access_method", None)+ # created_via is set at creation time and cannot be mutated afterwards+ validated_data.pop("created_via", None)++ if validated_data.get("auto_sync_new_schemas") and instance.is_direct_query:+ raise ValidationError(+ "Auto-syncing new schemas is not supported for direct query sources, "+ "because their schemas resolve at query time."+ )++ incoming_prefix = validated_data.get("prefix", instance.prefix)++ if instance.is_direct_query:+ # For direct query sources the prefix acts as the user-facing source name.+ normalized_prefix = incoming_prefix.strip() if isinstance(incoming_prefix, str) else ""+ if not normalized_prefix:+ raise ValidationError("Name is required for direct query sources")+ if ExternalDataSource.is_system_managed_prefix(normalized_prefix):+ raise ValidationError(helpers.RESERVED_SOURCE_NAME_MESSAGE)+ validated_data["prefix"] = normalized_prefix+ else:+ validated_data["prefix"] = instance.prefix++ existing_job_inputs = instance.job_inputs or {}+ job_inputs_were_submitted = "job_inputs" in validated_data+ incoming_job_inputs = validated_data.get("job_inputs", {})++ source_type_model = ExternalDataSourceType(instance.source_type)+ source = SourceRegistry.get_source(source_type_model)+ sensitive_fields = helpers.get_sensitive_field_names(source.get_source_config.fields)+ declared_field_names = helpers.get_declared_field_names(source.get_source_config.fields)+ discovered_schemas: list[SourceSchema] | None = None++ new_job_inputs = {**existing_job_inputs, **incoming_job_inputs}++ # CDC resource ownership changes must go through the CDC-specific endpoints.+ for key in helpers._CDC_EXPOSED_JOB_INPUT_KEYS:+ if key in existing_job_inputs:+ new_job_inputs[key] = existing_job_inputs[key]+ else:+ new_job_inputs.pop(key, None)++ # Server-managed job_inputs (Custom's OAuth2 row pointer, GitHub's legacy `repository`+ # marker): pin each to the stored value so an editor can't repoint the source at a different+ # row/marker (and through it, different credentials). Re-entered auth_oauth2_* secrets flow+ # into the pinned row during credential validation. The source declares which fields these+ # are — the API never names the source type.+ for field in source.server_managed_job_input_fields(incoming_job_inputs, existing_job_inputs):+ if existing_job_inputs.get(field):+ new_job_inputs[field] = existing_job_inputs[field]+ else:+ new_job_inputs.pop(field, None)++ # If the connection target changed, require credentials to be re-entered. Covers+ # both the generic `host` field and source-specific URL fields like ServiceNow's+ # `instance_url`, so a stored credential can't be redirected to a new host.+ connection_host_changed = any(+ field in incoming_job_inputs+ and helpers.connection_target_changed(existing_job_inputs.get(field), incoming_job_inputs[field])+ for field in helpers._CONNECTION_TARGET_FIELDS+ )++ # Some sources keep their connection target in a differently named field (e.g. Okta's+ # `okta_domain`, Freshdesk's `subdomain`). Changing one would send the preserved credential+ # to a new host — the same exfiltration risk as a `host` change — so require re-entry too.+ connection_host_changed = connection_host_changed or any(+ field in incoming_job_inputs+ and helpers.connection_target_changed(existing_job_inputs.get(field), incoming_job_inputs[field])+ for field in source.connection_host_fields+ )++ # If the SSH tunnel's connection target changed, also require credentials. Without this an+ # editor could swap in a tunnel that routes the backend's auth to an attacker-controlled+ # server, exfiltrating the stored database credentials (VERIA-311).+ ssh_tunnel_changed = "ssh_tunnel" in incoming_job_inputs and helpers.ssh_tunnel_connection_changed(+ existing_job_inputs.get("ssh_tunnel"),+ incoming_job_inputs.get("ssh_tunnel"),+ )++ # Some sources keep their connection target somewhere other than a named field — Custom's+ # lives inside its manifest. An edit that introduces a new request host would send the+ # preserved credential somewhere it wasn't going before, the same exfiltration risk, so+ # require re-entry too. The source decides; the API never names the source type.+ job_inputs_host_added = source.job_inputs_add_connection_host(incoming_job_inputs, existing_job_inputs)++ # Some sources keep their secrets in a bound row, not job_inputs (Custom's+ # CustomOAuth2Integration) — the generic preserved-credentials check can't see those, yet a+ # host change would still redirect the row's injected token. The source reports whether such+ # row-backed secrets are preserved (not re-entered) on this update.+ preserved_row_backed_credentials = source.has_preserved_row_backed_credentials(instance, incoming_job_inputs)++ if connection_host_changed or ssh_tunnel_changed or job_inputs_host_added:+ gate_sensitive_fields = sensitive_fields - helpers._CREATION_ONLY_SECRET_FIELDS+ preserved_credentials = helpers.has_preserved_credentials(+ existing_job_inputs,+ incoming_job_inputs,+ gate_sensitive_fields,+ nested_containers=(*helpers._NESTED_AUTH_CONTAINERS, *declared_field_names.switch_groups),+ )+ if preserved_credentials or preserved_row_backed_credentials:+ if ssh_tunnel_changed:+ raise ValidationError("Changing the SSH tunnel requires re-entering your database credentials.")+ if job_inputs_host_added:+ raise ValidationError("Changing the manifest's request host requires re-entering your credentials.")+ raise ValidationError("Changing the connection host requires re-entering your credentials.")++ # Preserve sensitive credentials not explicitly provided (API response omits them for security)+ for key in sensitive_fields:+ if existing_job_inputs.get(key) and not incoming_job_inputs.get(key):+ new_job_inputs[key] = existing_job_inputs[key]++ # SSH tunnel is a nested config - deep-merge it so partial updates preserve existing fields+ existing_ssh_tunnel = existing_job_inputs.get("ssh_tunnel")++ # Nested containers (e.g. Stripe `auth_method`, Snowflake `auth_type`, Billomat `registered_app`)+ # need a deep-merge that preserves sensitive fields not explicitly provided. The shallow merge+ # above would otherwise wipe redacted credentials nested inside these containers. Same container+ # list as the host-change gate above, so a merge here always has a matching preserved-credential check.+ for container_key in helpers._NESTED_AUTH_CONTAINERS:+ existing_container = existing_job_inputs.get(container_key)+ incoming_container = incoming_job_inputs.get(container_key)+ if incoming_container is not None and not isinstance(incoming_container, dict):+ raise ValidationError({"job_inputs": {container_key: "Must be an object."}})+ if not (isinstance(existing_container, dict) and isinstance(incoming_container, dict)):+ continue+ selection_changed = existing_container.get("selection") != incoming_container.get("selection")+ if selection_changed:+ # Selection switched (e.g. password→keypair) — use only incoming, don't carry over old secrets+ new_job_inputs[container_key] = incoming_container+ else:+ merged_container = {**existing_container, **incoming_container}+ for key in sensitive_fields:+ if existing_container.get(key) and not incoming_container.get(key):+ merged_container[key] = existing_container[key]+ new_job_inputs[container_key] = merged_container++ # Switch groups are nested containers too. The settings form submits only the fields the+ # user touched and skips a disabled group's children, so a payload that just flips+ # `enabled` would otherwise replace the whole stored group and drop a required nested+ # value that validation then rejects. Switching a group off keeps its stored value —+ # the user hasn't asked to forget it, and consumers gate on `enabled` before reading it.+ for group_key in declared_field_names.switch_groups:+ # A group declared with a hyphen can be stored under either spelling (see+ # `restore_declared_field_names`), so resolve both sides by declared name.+ incoming_key = helpers._stored_key(incoming_job_inputs, group_key)+ if incoming_key is None:+ continue+ incoming_group = incoming_job_inputs[incoming_key]+ if not isinstance(incoming_group, dict):+ raise ValidationError({"job_inputs": {group_key: "Must be an object."}})+ existing_group = helpers._stored_value(existing_job_inputs, group_key)+ if not isinstance(existing_group, dict):+ continue+ merged_group = {**existing_group, **incoming_group}+ # No switch group declares a secret today, but keep the carry-over so one could.+ for key in sensitive_fields:+ if existing_group.get(key) and not incoming_group.get(key):+ merged_group[key] = existing_group[key]+ # Drop the other spelling so parsing can't see two competing groups.+ for key in helpers._name_variants(group_key):+ new_job_inputs.pop(key, None)+ new_job_inputs[incoming_key] = merged_group++ incoming_ssh_tunnel = incoming_job_inputs.get("ssh_tunnel")+ if existing_ssh_tunnel and incoming_ssh_tunnel is not None:+ ssh_tunnel_host_changed = "host" in incoming_ssh_tunnel and incoming_ssh_tunnel[+ "host"+ ] != existing_ssh_tunnel.get("host")++ # Deep-merge: start with existing, overlay incoming top-level keys+ merged_ssh_tunnel = {**existing_ssh_tunnel, **incoming_ssh_tunnel}++ # Check both 'auth' (new format) and 'auth_type' (legacy format from migration 0807)+ existing_auth = (+ (existing_ssh_tunnel or {}).get("auth") or (existing_ssh_tunnel or {}).get("auth_type") or {}+ )+ incoming_auth = (+ (incoming_ssh_tunnel or {}).get("auth") or (incoming_ssh_tunnel or {}).get("auth_type") or {}+ )++ if ssh_tunnel_host_changed and not incoming_auth:+ raise ValidationError("Changing the SSH tunnel host requires re-entering your SSH credentials.")++ if not incoming_auth:+ # No auth in incoming request - preserve entire existing auth+ merged_ssh_tunnel["auth"] = {**existing_auth}+ else:+ # Merge auth, preserving sensitive fields not explicitly provided+ merged_auth = {**incoming_auth}+ if not ssh_tunnel_host_changed:+ for key in ("password", "passphrase", "private_key"):+ if existing_auth.get(key) and not incoming_auth.get(key):+ merged_auth[key] = existing_auth[key]+ merged_ssh_tunnel["auth"] = merged_auth++ new_job_inputs["ssh_tunnel"] = merged_ssh_tunnel++ is_valid, errors = source.validate_config(new_job_inputs)+ if not is_valid:+ raise ValidationError(f"Invalid source config: {', '.join(errors)}")++ # Clearing a multi-schema source's namespace migrates legacy rows to qualified naming.+ old_schema = detect_sql_schema_clear_transition(+ source_type=instance.source_type,+ existing_job_inputs=existing_job_inputs,+ incoming_job_inputs=incoming_job_inputs,+ )+ if old_schema is not None:+ apply_sql_warehouse_schema_clear_migration(instance, old_schema)++ source_config: Config = source.parse_config(new_job_inputs)+ validated_job_inputs = source_config.to_dict()++ # The settings form resubmits the whole connection config on every save, so changing an+ # unrelated setting (auto-syncing new tables, the prefix, the description) re-probed the+ # live connection too — and a momentarily unreachable database then failed the whole save,+ # leaving nothing to do but retry. Compare the parsed config against what's stored so the+ # probe below only runs when the connection actually changed. Direct query sources still+ # probe on every save: the same call refreshes their schemas and connection metadata.+ try:+ stored_job_inputs = source.parse_config(existing_job_inputs).to_dict()+ except Exception:+ # A stored config that no longer parses can't be compared, so treat it as changed and+ # let the probe run rather than skipping validation on a config we can't read.+ stored_job_inputs = None+ connection_config_changed = stored_job_inputs is None or stored_job_inputs != validated_job_inputs++ for key in helpers._CDC_EXPOSED_JOB_INPUT_KEYS:+ if key in existing_job_inputs:+ validated_job_inputs[key] = existing_job_inputs[key]+ validated_data["job_inputs"] = validated_job_inputs++ if job_inputs_were_submitted and (connection_config_changed or instance.is_direct_query):+ effective_api_version = source.resolve_api_version(instance.api_version)+ try:+ if isinstance(source, (PostgresSource, MySQLSource)):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config),+ instance.team_id,+ instance.access_method,+ api_version=effective_api_version,+ )+ elif isinstance(source, CustomSource):+ # Pass the source being updated so an integration-backed OAuth2 source can only validate+ # with the integration bound to it — not another source's, whose token the probe would+ # otherwise mint and send to the submitted manifest host. owner_user_id additionally gates+ # an as-yet-unbound integration to its creator.+ credentials_valid, credentials_error = source.validate_credentials(+ source_config,+ instance.team_id,+ source_id=str(instance.pk),+ owner_user_id=self.context["request"].user.id,+ api_version=effective_api_version,+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(+ source_config, instance.team_id, api_version=effective_api_version+ )+ except Exception as e:+ credentials_valid, credentials_error = helpers._credentials_validation_failed(+ source, instance.team_id, e+ )+ if not credentials_valid:+ raise ValidationError(credentials_error or helpers.INVALID_CREDENTIALS_FALLBACK_MESSAGE)+ if instance.is_direct_query:+ discovered_schemas = source.get_schemas(+ source_config, instance.team_id, api_version=effective_api_version+ )+ validated_data["connection_metadata"] = helpers.get_direct_connection_metadata(+ source_impl=source,+ source_config=source_config,+ team_id=instance.team_id,+ source_model=instance,+ fallback=instance.connection_metadata,+ )++ if job_inputs_were_submitted and isinstance(source, CustomSource):+ # Credential validation adopts re-entered OAuth2 secrets into the integration row and+ # rewrites the config (pointer set, static secrets cleared) — re-serialize so job_inputs+ # stores the pointer and never the raw secrets.+ validated_job_inputs = source_config.to_dict()+ for key in helpers._CDC_EXPOSED_JOB_INPUT_KEYS:+ if key in existing_job_inputs:+ validated_job_inputs[key] = existing_job_inputs[key]+ validated_data["job_inputs"] = validated_job_inputs++ # Namespaced-resource sources (GitHub repos) track their schema rows against a resource+ # set in job_inputs; capture the old set before the write so we can reconcile after.+ namespaced_adapter = get_namespaced_resource_adapter(source_type_model)+ old_namespaced_resources: list[str] = []+ if namespaced_adapter is not None and job_inputs_were_submitted:+ old_namespaced_resources = namespaced_adapter.resources_for_job_inputs(existing_job_inputs)++ updated_source: ExternalDataSource = super().update(instance, validated_data)++ if namespaced_adapter is not None and job_inputs_were_submitted:+ # Adds schema rows for added resources, retires removed ones, and reconciles their+ # webhooks. No-op when the effective resource list didn't change.+ namespaced_adapter.reconcile_resources(+ source_model=updated_source,+ team=instance.team,+ old_resources=old_namespaced_resources,+ new_config=source_config,+ )++ if updated_source.is_direct_query and discovered_schemas is not None:+ schema_names = {schema.name: schema.label for schema in discovered_schemas}+ descriptions = {schema.name: schema.description for schema in discovered_schemas}++ with transaction.atomic():+ ExternalDataSource._base_manager.filter(pk=updated_source.pk).select_for_update().get()+ engine = get_direct_query_engine(updated_source.direct_engine)+ name_substitutions = helpers._refresh_name_substitutions(+ engine, source=updated_source, source_schemas=discovered_schemas, team_id=instance.team_id+ )+ if name_substitutions:+ schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}+ descriptions = {+ name_substitutions.get(name, name): description for name, description in descriptions.items()+ }+ sync_old_schemas_with_new_schemas(+ schema_names,+ source_id=str(updated_source.id),+ team_id=instance.team_id,+ descriptions=descriptions,+ )+ # Direct call on the engine adapter (not the source hook) so tests mocking+ # `SourceRegistry.get_source` still exercise the real DataWarehouseTable rebuild.+ if engine is not None:+ engine.reconcile_schemas(+ source=updated_source, source_schemas=discovered_schemas, team_id=instance.team_id+ )++ schemas = list(+ ExternalDataSchema.objects.filter(team_id=instance.team_id, source_id=updated_source.id)+ .exclude(deleted=True)+ # This is the update() response path, which serializes the full column shape+ # (include_columns=True) — building columns reads table.credential.access_key per schema,+ # so keep the credential joined here to avoid an N+1.+ .select_related("table__credential", "table__external_data_source")+ .order_by("name")+ )+ # `get_status`/`get_latest_error` derive the active/errored subset from this prefetch, so no+ # separate `active_schemas` query is needed.+ updated_source_any = cast(Any, updated_source)+ updated_source_any._prefetched_objects_cache = {"schemas": schemas}++ return updated_source+++class ExternalDataSourceCreateSerializer(serializers.Serializer):+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type (e.g. 'Postgres', 'Stripe').",+ )+ payload = serializers.DictField(+ help_text=(+ "Connection credentials. Keys depend on source_type. Add a 'schemas' array to pick "+ "which tables sync; omit it and every discovered table syncs with default settings."+ ),+ )+ prefix = serializers.CharField(+ max_length=100,+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Prefix added to the table names PostHog creates in HogQL. Does not filter which tables are imported.",+ )+ description = serializers.CharField(+ max_length=400, required=False, allow_null=True, allow_blank=True, help_text="Human-readable description."+ )+ access_method = serializers.ChoiceField(+ choices=ExternalDataSource.AccessMethod.choices,+ required=False,+ default=ExternalDataSource.AccessMethod.WAREHOUSE,+ help_text="Connection mode: 'warehouse' (import) or 'direct' (live query).",+ )+ created_via = serializers.ChoiceField(+ # `wizard` and `self_driving` are intentionally omitted: they are never accepted from a+ # caller (that would let any client self-label as wizard- or self-driving-created). They+ # are derived server-side by upgrading a machine-injected `mcp` value based on the request+ # transport (the wizard, PostHog Desktop, or the wizard's self-driving program).+ choices=[+ ExternalDataSource.CreatedVia.WEB,+ ExternalDataSource.CreatedVia.API,+ ExternalDataSource.CreatedVia.MCP,+ ],+ required=False,+ default=ExternalDataSource.CreatedVia.API,+ help_text=(+ "Where the request came from: `web` for the in-app UI, `api` for direct API callers, "+ "`mcp` for agent/MCP tool calls. `wizard` and `self_driving` cannot be set directly — "+ "they are derived server-side for wizard- and PostHog Desktop-driven MCP calls. Defaults to `api`."+ ),+ )+ direct_query_enabled = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Whether a synced source should also be live-queryable via direct connection. "+ "Defaults to false; ignored for pure direct-query sources."+ ),+ )+ destination_ids = serializers.ListField(+ child=serializers.UUIDField(),+ required=False,+ help_text=(+ "Destinations every table on this source writes to. Set here rather than afterwards, "+ "so the opening sync already carries them. Omit to write to the PostHog warehouse only."+ ),+ )+++class SourceSetupSerializer(serializers.Serializer):+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type to set up (e.g. 'Stripe', 'Postgres', 'Hubspot').",+ )+ payload = serializers.DictField(+ required=False,+ help_text=(+ "Connection details as flat keys for the source_type (discover required fields with the wizard "+ "tool). Prefer references over raw secrets: pass {'credential_id': <id>} referencing the connection "+ "details the user stored via the connect-link page (discover ids with the stored_credentials "+ "endpoint) — they are merged in server-side and deleted once consumed. An already-connected OAuth "+ "integration can be passed via its id key instead (e.g. {'hubspot_integration_id': 123}). "+ "For source_type 'Custom' (a user-defined REST API) the keys are 'manifest_json' (a stringified "+ "RESTAPIConfig describing client.base_url, auth, and resources) plus the credential for the auth "+ "type the manifest declares — 'auth_token' (bearer), 'auth_api_key' (api_key), or 'auth_password' "+ "(http_basic); keep secrets in these auth_* keys, never inline in the manifest. "+ "A 'schemas' array is NOT required — all discovered tables are enabled automatically with sensible "+ "sync defaults."+ ),+ )+ prefix = serializers.CharField(+ max_length=100,+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text=(+ "Prefix added to the table names PostHog creates in HogQL, e.g. 'stripe' produces stripe_charges. "+ "Does not filter which tables are imported. Defaults to the source type."+ ),+ )+ description = serializers.CharField(+ max_length=400, required=False, allow_null=True, allow_blank=True, help_text="Human-readable description."+ )+ direct_query_enabled = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Whether a synced source should also be live-queryable via direct connection. "+ "Defaults to false; ignored for pure direct-query sources."+ ),+ )+++class SourceSetupResponseSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="ID of the created external data source.")+ webhook = webhook_setup.SourceSetupWebhookSerializer(+ required=False,+ help_text=(+ "Outcome of automatic webhook registration. Only present for sources that support webhooks "+ "(e.g. Stripe) and have webhook-capable tables."+ ),+ )+++class ExternalDataSourceCreateResponseSerializer(serializers.Serializer):+ id = serializers.UUIDField(help_text="ID of the created external data source.")+++class ExternalDataSourceErrorResponseSerializer(serializers.Serializer):+ message = serializers.CharField(help_text="Human-readable explanation of why the source could not be created.")+++class SourcePreviewRequestSerializer(serializers.Serializer):+ source_type = serializers.ChoiceField(+ choices=ExternalDataSourceType.choices,+ help_text="The source type to preview. Only 'Custom' (a user-defined REST API) is supported today.",+ )+ payload = serializers.DictField(+ required=False,+ help_text=(+ "Source config as flat keys. For source_type 'Custom': 'manifest_json' (a stringified RESTAPIConfig "+ "describing client.base_url, auth, and resources) plus the credential for the manifest's declared auth "+ "type — 'auth_token' (bearer), 'auth_api_key' (api_key), or 'auth_password' (http_basic). Secrets stay "+ "in these auth_* keys, never inline in the manifest."+ ),+ )+ resource_name = serializers.CharField(+ help_text="Which manifest resource (table) to read a sample from — one of the resource names in manifest_json.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=PREVIEW_DEFAULT_ROWS,+ min_value=1,+ max_value=PREVIEW_MAX_ROWS,+ help_text=f"Maximum sample rows to return (1–{PREVIEW_MAX_ROWS}). Defaults to {PREVIEW_DEFAULT_ROWS}.",+ )+++class SourcePreviewColumnSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Column name as it appears in the previewed rows.")+ type = serializers.CharField(+ help_text="JSON type inferred from the first non-null value: string, integer, number, boolean, object, array, or null."+ )+++class SourcePreviewResponseSerializer(serializers.Serializer):+ rows = serializers.ListField(+ child=serializers.DictField(),+ help_text="Up to `limit` sample rows, after data_selector extraction — the raw records the sync would ingest.",+ )+ row_count = serializers.IntegerField(help_text="Number of sample rows returned (≤ limit).")+ columns = SourcePreviewColumnSerializer(+ many=True,+ help_text="Columns observed across the sample rows, each with an inferred JSON type.",+ )+ error = serializers.CharField(+ allow_null=True,+ help_text=(+ "Set when the live read failed (e.g. the host was unreachable or returned an auth error); rows is then "+ "empty. Manifest, validation, and SSRF problems return HTTP 400 instead of populating this field."+ ),+ )+++class DraftCustomManifestRequestSerializer(serializers.Serializer):+ source_name = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ help_text="Optional human name of the API being connected (e.g. 'Acme CRM'). Used only to orient the model.",+ )+ docs_url = serializers.URLField(+ required=False,+ allow_blank=True,+ help_text="URL of the API documentation to read. Provide this or docs_text; fetched server-side via the egress proxy.",+ )+ docs_text = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text="Raw API documentation or an OpenAPI/Swagger spec, pasted directly. Provide this or docs_url.",+ )++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ # Strip first: a whitespace-only docs_text is truthy but useless (it'd fetch an empty URL).+ if not ((attrs.get("docs_url") or "").strip() or (attrs.get("docs_text") or "").strip()):+ raise serializers.ValidationError("Provide either docs_url or docs_text.")+ return attrs+++class DraftCustomManifestResponseSerializer(serializers.Serializer):+ draft_status = serializers.ChoiceField(+ choices=["ok", "invalid", "model_error"],+ help_text=(+ "'ok' = a manifest validated; 'invalid' = a manifest was drafted but never validated within the budget "+ "(see error; manifest_json holds the last attempt to fix by hand); 'model_error' = the model returned no "+ "usable JSON."+ ),+ )+ manifest_json = serializers.CharField(+ allow_null=True,+ help_text="The drafted RESTAPIConfig manifest as a JSON string (non-secret), or null if none was produced.",+ )+ resource_names = serializers.ListField(+ child=serializers.CharField(),+ help_text="Names of the resources (tables) the validated manifest exposes. Empty unless draft_status is 'ok'.",+ )+ attempts = serializers.IntegerField(+ help_text="How many draft→validate→repair rounds were run.",+ )+ error = serializers.CharField(+ allow_null=True,+ help_text="The last validation error when draft_status is not 'ok'; null on success.",+ )+++class SimpleExternalDataSourceSerializers(serializers.ModelSerializer):+ class Meta:+ model = ExternalDataSource+ fields = [+ "id",+ "created_at",+ "created_by",+ "status",+ "source_type",+ ]+ read_only_fields = ["id", "created_by", "created_at", "status", "source_type"]+++class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):+ def _resolve_stored_credential(self, source_type: str, payload: dict) -> credential_store.ResolvedStoredCredential:+ """Merge a connect-link stored credential into `payload` when it carries a `credential_id`.++ Lets the create and setup flows reference credentials the user entered on the connect page+ instead of passing secrets inline. Only credentials the requesting user stored resolve —+ ids are listable within a team, so without the owner check any member could consume a+ teammate's stashed secrets into a source they control. Returns the (possibly merged)+ payload, the resolved credential (which the caller deletes once consumed — stored+ credentials are single-use), and a 400 Response to return as-is on a lookup miss or+ source-type mismatch.+ """+ credential_id = payload.pop("credential_id", None)+ if credential_id is None:+ return credential_store.ResolvedStoredCredential(payload=payload, credential=None, error_response=None)+ try:+ credential = PendingSourceCredential.objects.for_team(self.team_id).get(+ id=credential_id, created_by=cast(User, self.request.user), expires_at__gt=timezone.now()+ )+ except (PendingSourceCredential.DoesNotExist, ValueError, TypeError, DjangoValidationError):+ return credential_store.ResolvedStoredCredential(+ payload=payload,+ credential=None,+ error_response=Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Stored credential '{credential_id}' not found or expired"},+ ),+ )+ if credential.source_type != source_type:+ return credential_store.ResolvedStoredCredential(+ payload=payload,+ credential=None,+ error_response=Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Stored credential '{credential_id}' is for "+ f"'{credential.source_type}', not '{source_type}'"+ },+ ),+ )+ # Stored credentials win over inline keys so an agent can't override what the user entered.+ return credential_store.ResolvedStoredCredential(+ payload={**payload, **credential.payload}, credential=credential, error_response=None+ )++ @extend_schema(+ request=ExternalDataSourceCreateSerializer,+ responses={201: ExternalDataSourceCreateResponseSerializer},+ )+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ source_type = serializer.validated_data["source_type"]+ payload = dict(serializer.validated_data["payload"] or {})++ secret_ref_response = credential_store._unresolved_secret_ref_response(payload)+ if secret_ref_response is not None:+ return secret_ref_response++ # A `credential_id` in the payload references connection details the user entered on the+ # connect-link page — resolve it to the real secrets so `create` can target a specific+ # `schemas` set (unlike `setup`, which discovers and enables every table).+ resolved = self._resolve_stored_credential(source_type, payload)+ if resolved.error_response is not None:+ return resolved.error_response++ response = self._create_external_data_source(+ request,+ source_type=source_type,+ payload=resolved.payload,+ prefix=serializer.validated_data.get("prefix"),+ description=serializer.validated_data.get("description"),+ access_method=serializer.validated_data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE),+ created_via=serializer.validated_data.get("created_via", ExternalDataSource.CreatedVia.API),+ direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),+ destination_ids=serializer.validated_data.get("destination_ids"),+ )+ # Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.+ if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:+ resolved.credential.delete()+ return response++ def perform_update(self, serializer: serializers.BaseSerializer) -> None:+ # Runs for both PUT and PATCH (DRF's partial_update delegates to update -> perform_update).+ # `created_via` is write-once and reflects original creation origin; the edit's own origin+ # comes from the request-derived `source` that report_user_action attaches.+ super().perform_update(serializer)+ instance = cast(ExternalDataSource, serializer.instance)+ report_user_action(+ cast(User, self.request.user),+ "data warehouse source updated",+ {+ "source_type": instance.source_type,+ "created_via": instance.created_via,+ "source_id": str(instance.pk),+ },+ team=self.team,+ request=self.request,+ )++ def _create_external_data_source(+ self,+ request: Request,+ *,+ source_type: str,+ payload: dict,+ prefix: str | None,+ description: str | None,+ access_method: str,+ created_via: str,+ direct_query_enabled: bool = False,+ skip_credential_validation: bool = False,+ destination_ids: list | None = None,+ ) -> Response:+ # `skip_credential_validation` is set only by the `setup` action, which has already run the+ # full config + credential gate (including the SSRF host check) before discovering schemas.+ # It avoids a second live credential round-trip — and the confusing failure mode where the+ # first check passes but a transient blip fails the second, leaving nothing created.++ # The setup wizard and PostHog's agent surfaces drive creation through the MCP tools, which+ # inject `created_via=mcp` before the request reaches us — the agent can't set the field+ # itself. Upgrade that machine-injected value when the transport identifies one of them, so+ # their runs are distinguishable from other MCP clients. Explicit `web`/`api` values are+ # left alone. The PostHog apps and the headless agents all map to `self_driving`: the+ # distinction between them is an analytics one, and splitting it here would need a new+ # stored value.+ if created_via == ExternalDataSource.CreatedVia.MCP:+ transport_created_via = {+ EventSource.WIZARD: ExternalDataSource.CreatedVia.WIZARD,+ EventSource.DESKTOP: ExternalDataSource.CreatedVia.SELF_DRIVING,+ EventSource.MOBILE: ExternalDataSource.CreatedVia.SELF_DRIVING,+ EventSource.POSTHOG_CODE: ExternalDataSource.CreatedVia.SELF_DRIVING,+ EventSource.SELF_DRIVING: ExternalDataSource.CreatedVia.SELF_DRIVING,+ }+ created_via = transport_created_via.get(get_event_source(request), created_via)+ # The wizard's `self-driving` onboarding program shares the generic `posthog/wizard`+ # transport but marks its UA distinctly — attribute its sources as self_driving too, so+ # a source connected during a self-driving run isn't lumped in with plain wizard setups.+ if created_via == ExternalDataSource.CreatedVia.WIZARD and is_wizard_self_driving_program(request):+ created_via = ExternalDataSource.CreatedVia.SELF_DRIVING+ is_direct_query = access_method == ExternalDataSource.AccessMethod.DIRECT++ if ExternalDataSource.is_system_managed_prefix(prefix):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers.RESERVED_SOURCE_NAME_MESSAGE},+ )++ if is_direct_query and source_type not in direct_capable_source_types():+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers.DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},+ )++ if is_direct_query:+ prefix = prefix.strip() if isinstance(prefix, str) else ""+ if not prefix:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Name is required for direct query sources"},+ )+ else:+ is_valid, error_message = validate_source_prefix(prefix)+ if not is_valid:+ raise ValidationError(error_message)++ if not prefix:+ if self.prefix_required(source_type):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": "You already have a source of this type. Add a table prefix so this connection's tables don't clash with your existing source."+ },+ )+ elif self.prefix_exists(source_type, prefix):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Another source of this type already uses the prefix '{prefix}'. Choose a different prefix so this connection's tables don't clash."+ },+ )++ if access_method == ExternalDataSource.AccessMethod.WAREHOUSE and is_any_external_data_schema_paused(+ self.team_id+ ):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},+ )++ # Strip leading and trailing whitespace+ if payload is not None:+ for key, value in payload.items():+ if isinstance(value, str):+ payload[key] = value.strip()+ source_type_model = ExternalDataSourceType(source_type)+ source = base.SourceRegistry.get_source(source_type_model)+ if not is_direct_query and not source.supports_scheduled_sync:+ return Response(+ ExternalDataSourceErrorResponseSerializer(+ {"message": f"{source_type_model.label} is available only as a direct connection."}+ ).data,+ status=status.HTTP_400_BAD_REQUEST,+ )+ max_instances = source.max_instances_per_team+ if max_instances is not None and helpers.count_active_sources(self.team_id, source_type_model) >= max_instances:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"You can create at most {max_instances} sources of this type per project."},+ )+ if skip_credential_validation:+ source_config: Config = source.parse_config(payload)+ else:+ error_response, validated_config = self._validate_source_config_and_credentials(+ source, source_type_model, payload, access_method=access_method+ )+ if error_response is not None or validated_config is None:+ return error_response or Response(status=status.HTTP_400_BAD_REQUEST)+ source_config = validated_config++ new_source_model = ExternalDataSource.objects.create(+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ created_by=request.user if isinstance(request.user, User) else None,+ created_via=created_via,+ team=self.team,+ status="Running",+ source_type=source_type_model,+ api_version=source.default_version,+ job_inputs=source_config.to_dict(),+ prefix=prefix,+ description=description,+ access_method=access_method,+ direct_query_enabled=direct_query_enabled,+ )++ # Post-create hook (Custom claims its bound OAuth2 integration row here). No-op otherwise.+ source.on_source_created(new_source_model, self.team_id)++ # CDC: gate per-source-type adapter availability up front so downstream blocks+ # can `if cdc_enabled` without repeating the source-type check.+ try:+ cdc_adapter: CDCSourceAdapter | None = get_cdc_adapter(new_source_model)+ except ValueError:+ cdc_adapter = None+ cdc_enabled = (+ payload.get("cdc_enabled", False) and cdc_adapter is not None and base.is_cdc_enabled_for_team(self.team)+ )++ try:+ source_schemas = source.get_schemas(+ source_config, self.team_id, api_version=source.resolve_api_version(new_source_model.api_version)+ )+ except NotImplementedError:+ # Source doesn't implement schema discovery (e.g. an unreleased scaffold the UI hides).+ # Roll back the row just created so a caller can't accumulate orphaned sources, and return+ # a clean 400 instead of the uncaught 500 this would otherwise raise. Mirrors `setup`.+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers._source_unavailable_message(source_type)},+ )+ except Exception as e:+ # `get_schemas` opens its own connection, so credentials validated above can still fail+ # here (e.g. a BigQuery service account key rotated/revoked in between). Classify via+ # the source's own non-retryable-error map, same as `database_schema` and+ # `refresh_schemas`, and roll back the row so a source that can't discover its schema+ # doesn't linger half-created.+ error_message, is_expected_source_error = helpers._classify_refresh_schemas_error(source, e)+ if not is_expected_source_error:+ base.capture_exception(+ e,+ {+ "source_type": source_type,+ "team_id": self.team_id,+ "source_id": str(new_source_model.id),+ },+ )+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": error_message},+ )+ if is_direct_query:+ new_source_model.connection_metadata = helpers.get_direct_connection_metadata(+ source_impl=source,+ source_config=source_config,+ team_id=self.team_id,+ source_model=new_source_model,+ )+ new_source_model.save(update_fields=["connection_metadata", "updated_at"])+ source_schemas_by_name = {schema.name: schema for schema in source_schemas}+ schema_names = [schema.name for schema in source_schemas]+ source_config_dict = source_config.to_dict()+ default_source_schema = source_config_dict.get("schema")+ default_source_catalog = source_config_dict.get("database") or source_config_dict.get("catalog")+ schema_label_by_name = {s.name: s.label for s in source_schemas}++ # Omitting `schemas` means "sync what you found", the same defaults `setup` builds. A+ # caller that wants to hand-pick tables still sends the array; one that just has+ # credentials no longer has to run schema discovery itself to write back what we already+ # know. Discovery ran above, so the defaults cost nothing extra here.+ payload_schemas = payload.get("schemas")+ if payload_schemas is not None and not isinstance(payload_schemas, list):+ new_source_model.delete()+ return Response(+ data={"message": "The 'schemas' field must be a list of the tables to sync."},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if not payload_schemas:+ payload_schemas = build_default_schemas(source_schemas)++ # Return 400 if we get any schema names that don't exist in our source+ if any(schema.get("name") not in schema_names for schema in payload_schemas):+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Schemas given do not exist in source"},+ )++ # Refuse per-schema `sync_type=cdc` when source-level CDC is off — `_setup_cdc_resources`+ # would be skipped, leaving the source with no replication slot/publication.+ if not cdc_enabled:+ cdc_schemas_in_payload = sorted(+ {+ schema["name"]+ for schema in payload_schemas+ if schema.get("sync_type") == "cdc"+ and schema.get("should_sync", False)+ and isinstance(schema.get("name"), str)+ }+ )+ if cdc_schemas_in_payload:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": (+ "CDC must be enabled on the source before selecting it as a sync type. "+ f"The following schemas requested CDC: {', '.join(cdc_schemas_in_payload)}."+ )+ },+ )++ active_schemas: list[ExternalDataSchema] = []++ # Pre-fetch PK column names for CDC tables+ pk_columns_by_table: dict[str, list[str]] = {}+ if cdc_enabled:+ cdc_table_names_by_schema: dict[str, set[str]] = {}+ cdc_schema_name_by_location: dict[tuple[str, str], str] = {}+ for schema in payload_schemas:+ if schema.get("sync_type") != "cdc" or not schema.get("should_sync", False):+ continue++ schema_name = schema.get("name")+ if not isinstance(schema_name, str):+ continue++ _, resolved_source_schema, resolved_source_table_name = helpers.get_postgres_source_table_location(+ schema_name=schema_name,+ source_schema=source_schemas_by_name.get(schema_name),+ default_schema=default_source_schema,+ )+ cdc_table_names_by_schema.setdefault(resolved_source_schema, set()).add(resolved_source_table_name)+ cdc_schema_name_by_location[(resolved_source_schema, resolved_source_table_name)] = schema_name++ if cdc_table_names_by_schema:+ try:+ with base.cdc_pg_connection(new_source_model) as conn:+ for db_schema, cdc_table_names in cdc_table_names_by_schema.items():+ queried_pks = base.get_primary_key_columns(conn, db_schema, list(cdc_table_names))+ for table_name, primary_key_columns in queried_pks.items():+ schema_name = cdc_schema_name_by_location.get((db_schema, table_name))+ if schema_name is not None:+ pk_columns_by_table[schema_name] = primary_key_columns+ except base._EXPECTED_CONNECTION_ERRORS as e:+ # Connecting to the user's database to detect CDC primary keys is expected to+ # fail when the host, port, credentials, or SSH tunnel are wrong, or the server+ # requires/refuses SSL. Surface it as a 400, but don't capture it — these are+ # user/upstream connection problems, not bugs in our code, and capturing every+ # one floods error tracking. Mirrors the CDC-prerequisite handlers below.+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Could not connect to your database to set up change data capture: {e}"},+ )++ # CDC needs a PK for UPDATE/DELETE merges. Refuse here so `_setup_cdc_resources` doesn't+ # create replication state on the source for a config we're about to reject.+ tables_missing_pk = sorted(+ {+ schema["name"]+ for schema in payload_schemas+ if schema.get("sync_type") == "cdc"+ and schema.get("should_sync", False)+ and isinstance(schema.get("name"), str)+ and not pk_columns_by_table.get(schema["name"])+ }+ )+ if tables_missing_pk:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": (+ "CDC requires a primary key on each table. "+ f"The following tables have no primary key: {', '.join(tables_missing_pk)}."+ )+ },+ )++ # Engine-side CDC resource setup runs after PK validation so we don't leave+ # replication state on the source for a config we're about to refuse.+ if cdc_enabled:+ assert cdc_adapter is not None # narrowed by `cdc_enabled`+ cdc_error = self._setup_cdc_resources(cdc_adapter, new_source_model, payload)+ if cdc_error is not None:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": cdc_error},+ )++ # Direct-query table materialization is engine-specific; dispatch on the engine, not the+ # source type. None for non-direct-capable sources.+ direct_engine_adapter = get_direct_query_engine(new_source_model.direct_engine)++ # Create all ExternalDataSchema objects and enable syncing for active schemas+ for schema in payload_schemas:+ sync_type = schema.get("sync_type")+ requires_incremental_fields = sync_type == "incremental" or sync_type == "append"+ incremental_field = schema.get("incremental_field")+ incremental_field_type = schema.get("incremental_field_type")+ primary_key_columns = schema.get("primary_key_columns")+ sync_time_of_day = schema.get("sync_time_of_day")+ should_sync = schema.get("should_sync", False)+ payload_enabled_columns = schema.get("enabled_columns")+ if isinstance(payload_enabled_columns, list):+ # `[]` and `None` are distinct: `None` means sync all columns, `[]` means+ # sync only the always-retained PK + incremental field.+ enabled_columns: list[str] | None = [+ str(column) for column in payload_enabled_columns if isinstance(column, str)+ ]+ else:+ enabled_columns = None++ payload_row_filters = schema.get("row_filters")+ row_filters: list[dict[str, Any]] | None = (+ payload_row_filters if isinstance(payload_row_filters, list) and payload_row_filters else None+ )++ if should_sync and requires_incremental_fields and incremental_field is None:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Incremental schemas given do not have an incremental field set"},+ )++ if should_sync and requires_incremental_fields and incremental_field_type is None:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Incremental schemas given do not have an incremental field type set"},+ )++ schema_name = schema.get("name")+ source_schema = source_schemas_by_name.get(schema_name)++ metadata_source_catalog: str | None+ metadata_source_schema: str | None+ metadata_source_table_name: str | None+ # Direct mode needs a resolved source location for the live-query table; warehouse mode+ # keeps storing whatever the source reported to avoid changing sync routing (except+ # Postgres, which resolves in both modes — carried by the adapter flag).+ if direct_engine_adapter is not None and (+ is_direct_query or direct_engine_adapter.resolves_location_in_warehouse_mode+ ):+ metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (+ direct_engine_adapter.source_table_location(+ schema_name=schema_name,+ source_schema=source_schema,+ default_schema=default_source_schema,+ default_catalog=default_source_catalog,+ )+ )+ else:+ metadata_source_catalog = source_schema.source_catalog if source_schema else None+ metadata_source_schema = source_schema.source_schema if source_schema else None+ metadata_source_table_name = source_schema.source_table_name if source_schema else None++ schema_metadata = (+ sql_schema_metadata(+ source_schema.columns if source_schema else [],+ source_schema.foreign_keys if source_schema else [],+ source_catalog=metadata_source_catalog,+ source_schema=metadata_source_schema,+ source_table_name=metadata_source_table_name,+ )+ if source.supports_column_selection+ else {}+ )+ # Sources that namespace tables outside SQL schemas (e.g. GitHub repos) attach their+ # own location keys on the discovered schema; persist them so sync-time resolution+ # never depends on parsing the row name.+ if source_schema is not None and source_schema.schema_metadata:+ schema_metadata = {**schema_metadata, **source_schema.schema_metadata}++ if row_filters is not None:+ # Only sources that push filters into their query (SQL WHERE) can honor them — a+ # saved-but-ignored filter would silently sync unfiltered rows.+ if not source.supports_row_filters:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Row filter not allowed for schema '{schema_name}': "+ "row filters are not supported for this source type."+ },+ )+ if reason := unsupported_row_filter_reason(+ is_direct_query=new_source_model.is_direct_query, is_cdc=sync_type == "cdc"+ ):+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Row filter not allowed for schema '{schema_name}': {reason}"},+ )+ try:+ validate_and_coerce_row_filters(row_filters, schema_metadata)+ except RowFilterValidationError as e:+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid row filter for schema '{schema_name}': {e}"},+ )++ is_cdc_schema = sync_type == "cdc"+ # A CDC table the user isn't enabling hasn't been "set up" — leave its sync method+ # blank so the schemas UI prompts the user to configure it before it can sync, rather+ # than presetting `cdc` on every discovered table. Only tables the user actively+ # enables get a concrete CDC method + config.+ cdc_not_set_up = is_cdc_schema and not should_sync+ if requires_incremental_fields and new_source_model.supports_scheduled_sync:+ # If the caller didn't provide primary_key_columns, fall back to whatever the+ # source detected during schema discovery. Otherwise we rely on sync-time+ # re-detection, which can disagree with discovery (e.g. permissions differences+ # across query paths) and leave incremental syncs without a primary key.+ effective_primary_key_columns = primary_key_columns or (+ source_schema.detected_primary_keys if source_schema else None+ )+ # Lookback only applies to incremental (merge-by-PK makes the overlap re-read idempotent).+ # Mirror the schema-update path's IntegerField(min_value=0, max_value=5_184_000) so both+ # creation paths reject the same inputs instead of silently dropping null/float values.+ lookback_seconds = schema.get("incremental_field_lookback_seconds")+ # When the caller didn't set a lookback, fall back to the source-defined default+ # (e.g. Google Ads stats tables, whose recent rows Google keeps revising for days).+ # This loop is the single creation choke point, so the default reaches both the+ # wizard and one-shot flows; it's then validated by the bounds check just below.+ if lookback_seconds is None and source_schema is not None:+ lookback_seconds = source_schema.default_incremental_lookback_seconds+ if lookback_seconds is not None:+ # Coerce whole-number floats (e.g. 90.0) the way DRF's IntegerField does.+ if isinstance(lookback_seconds, float) and lookback_seconds.is_integer():+ lookback_seconds = int(lookback_seconds)+ # bool is an int subclass — exclude it so true/false aren't treated as 1/0.+ is_valid_int = isinstance(lookback_seconds, int) and not isinstance(lookback_seconds, bool)+ if not is_valid_int or not (0 <= lookback_seconds <= 5_184_000):+ new_source_model.delete()+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"incremental_field_lookback_seconds must be an integer between 0 and 5184000 (60 days) for schema '{schema_name}'."+ },+ )+ # Canonicalize the incremental field against what the source declares for this+ # endpoint: discovery surfaces both a display `label` and the underlying `field`+ # (e.g. Stripe's label "created_at" -> field "created"), and API callers regularly+ # send the label — which then fails every sync with a missing-column error. Match on+ # either and persist the declared field + its real field_type.+ if incremental_field is not None and source_schema is not None:+ for declared in source_schema.incremental_fields:+ if incremental_field in (declared["field"], declared["label"]):+ incremental_field = declared["field"]+ incremental_field_type = str(declared["field_type"])+ break++ sync_type_config = {+ "incremental_field": incremental_field,+ "incremental_field_type": incremental_field_type,+ "schema_metadata": schema_metadata,+ **({"primary_key_columns": effective_primary_key_columns} if effective_primary_key_columns else {}),+ **(+ {"incremental_field_lookback_seconds": lookback_seconds}+ if sync_type == "incremental" and lookback_seconds is not None+ else {}+ ),+ }+ elif is_cdc_schema and not cdc_not_set_up:+ cdc_table_mode = schema.get("cdc_table_mode", "consolidated")+ sync_type_config = {+ "cdc_mode": "snapshot",+ "primary_key_columns": pk_columns_by_table.get(schema_name, []),+ "schema_metadata": schema_metadata,+ "cdc_table_mode": cdc_table_mode,+ }+ else:+ sync_type_config = {"schema_metadata": schema_metadata}++ # CDC schemas benefit from a tighter poll cadence — the extraction workflow is cheap+ # and the value prop is near-real-time. Other sync types use the 6h default.+ schema_sync_frequency_interval = (+ timedelta(minutes=5)+ if is_cdc_schema and not cdc_not_set_up and new_source_model.supports_scheduled_sync+ else timedelta(hours=6)+ )+ schema_model = ExternalDataSchema.objects.create(+ name=schema_name,+ team=self.team,+ source=new_source_model,+ should_sync=should_sync,+ sync_type=(None if cdc_not_set_up else sync_type) if new_source_model.supports_scheduled_sync else None,+ sync_time_of_day=sync_time_of_day if new_source_model.supports_scheduled_sync else None,+ sync_type_config=sync_type_config,+ description=source_schema.description if source_schema else None,+ label=schema_label_by_name.get(schema_name),+ sync_frequency_interval=schema_sync_frequency_interval,+ enabled_columns=enabled_columns,+ row_filters=row_filters,+ )++ # The CDC path is Postgres-only, and the engine adapter's `source_table_location`+ # guarantees non-None schema/table when it resolves above. `cast` narrows for mypy+ # without a runtime check. The adapter no-ops for self-managed / no-publication.+ if is_cdc_schema and should_sync and cdc_enabled and cdc_adapter is not None:+ cdc_adapter.add_table(+ new_source_model,+ cast(str, metadata_source_schema),+ cast(str, metadata_source_table_name),+ )++ if direct_engine_adapter is not None and is_direct_query and should_sync:+ # Apply the picker's column subset on the very first DataWarehouseTable build,+ # not just on subsequent updates — otherwise users see all columns in HogQL until+ # they hit save again or a refresh runs. Columns are keyed by raw, case-sensitive+ # source names (`normalize=False`).+ schema_model.table = direct_engine_adapter.upsert_table(+ None,+ schema_name=schema_name,+ source=new_source_model,+ columns=filter_dwh_columns_by_enabled_columns(+ direct_engine_adapter.columns_to_dwh_columns(source_schema.columns if source_schema else []),+ enabled_columns,+ source_schema.detected_primary_keys if source_schema else None,+ incremental_field,+ normalize=False,+ ),+ source_catalog=metadata_source_catalog,+ source_schema=cast(str, metadata_source_schema),+ source_table_name=cast(str, metadata_source_table_name),+ )+ schema_model.save(update_fields=["table"])++ if should_sync and new_source_model.supports_scheduled_sync:+ active_schemas.append(schema_model)++ # Attach destinations before any schedule starts. Extraction snapshots the set onto the+ # run, so a source whose destinations arrive after its first sync began writes that run+ # to the warehouse alone, and reaching the others costs a full resync.+ if destination_ids:+ try:+ set_source_destinations(+ team_id=self.team_id,+ source_id=new_source_model.pk,+ destination_ids=destination_ids,+ )+ except Exception as e:+ # The source is already created and its tables are configured. Losing that over a+ # destination set the user can still fix on the Destinations tab is the worse trade.+ base.logger.exception(+ "Could not attach destinations to a new source",+ exc_info=e,+ source_id=new_source_model.pk,+ )++ # Create all sync schedules over a single shared Temporal connection. Creating them+ # one call at a time reconnects to Temporal on every iteration, which does not scale+ # to sources with thousands of schemas (e.g. a Slack workspace with thousands of+ # channels).+ try:+ schedule_errors = base.bulk_create_external_data_job_schedules(+ [(active_schema, active_schema.should_sync) for active_schema in active_schemas]+ )+ for schema_id, schedule_error in schedule_errors:+ # The source model was already created, so a partial schedule failure+ # shouldn't fail the request — log each failure and carry on.+ base.logger.exception(+ "Could not trigger external data job",+ exc_info=schedule_error,+ schema_id=schema_id,+ )+ except Exception as e:+ base.logger.exception("Could not trigger external data job", exc_info=e)++ # Per-source schema discovery schedule. Runs every 6h so newly added+ # upstream resources (Slack channels, Postgres tables, …) get picked up+ # without re-discovering on every per-schema sync tick. Direct-query+ # sources resolve schemas at query time, so they opt out of all+ # background sync — including this discovery cadence.+ if new_source_model.supports_scheduled_sync:+ try:+ base.sync_discover_schemas_schedule(new_source_model, create=True)+ except Exception as e:+ base.logger.exception("Could not create schema discovery schedule", exc_info=e)++ # Start CDC extraction schedule if any CDC schemas are active+ if cdc_enabled:+ try:+ base.sync_cdc_extraction_schedule(new_source_model, create=True)+ base.ensure_cdc_slot_cleanup_schedule()+ except Exception as e:+ base.logger.exception("Could not create CDC schedules", exc_info=e)++ if new_source_model.revenue_analytics_config_safe.enabled:+ managed_viewset, _ = DataWarehouseManagedViewSet.objects.get_or_create(+ team=self.team,+ kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,+ )+ managed_viewset.sync_views()+ base.ensure_person_join(self.team.pk, new_source_model.prefix)++ # `source` (web/api/mcp/wizard/posthog_code) is derived from the request by report_user_action;+ # `created_via` is the caller's explicit intent (with one exception: the machine-injected `mcp`+ # is upgraded above when the transport identifies the wizard or PostHog Desktop). They usually+ # agree but are kept separate so a transport change (e.g. a new wrapper UA) doesn't silently+ # rewrite historical attribution.+ report_user_action(+ cast(User, request.user),+ "data warehouse source created",+ {+ "source_type": source_type,+ "created_via": created_via,+ "source_access_method": access_method,+ "direct_query_enabled": direct_query_enabled,+ "schema_count": len(active_schemas),+ "source_id": str(new_source_model.pk),+ },+ team=self.team,+ request=request,+ )++ return Response(+ status=status.HTTP_201_CREATED,+ data=ExternalDataSourceCreateResponseSerializer({"id": new_source_model.pk}).data,+ )++ def prefix_required(self, source_type: str) -> bool:+ # A prefix is only needed when a no-prefix source of the same type already+ # exists. Two no-prefix sources would write to the same table names; sources+ # with distinct prefixes (including one no-prefix + N prefixed) have separate+ # table namespaces and cannot collide.+ no_prefix_source_exists = (+ ExternalDataSource.objects.exclude(deleted=True)+ .filter(team_id=self.team.pk, source_type=source_type)+ .filter(Q(prefix__isnull=True) | Q(prefix=""))+ .exists()+ )+ return no_prefix_source_exists++ def prefix_exists(self, source_type: str, prefix: str) -> bool:+ prefix_exists = (+ ExternalDataSource.objects.exclude(deleted=True)+ .filter(team_id=self.team.pk, source_type=source_type, prefix=prefix)+ .exists()+ )+ return prefix_exists++ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance: ExternalDataSource = self.get_object()++ schemas = list(+ ExternalDataSchema.objects.exclude(deleted=True)+ .filter(team_id=self.team_id, source_id=instance.id)+ .select_related("table")+ .all()+ )++ # Deleting the source deletes every table it synced, so it needs editor on each of them.+ self._assert_can_write_schemas(schemas)++ # Soft-delete source, schemas, tables, and companion _cdc tables atomically+ # first so DB state is consistent even if the external cleanup below fails+ with transaction.atomic():+ for schema in schemas:+ if schema.table:+ schema.table.soft_delete()++ # Bulk soft-delete the schema rows in a single UPDATE. Per-row soft_delete()+ # runs a SELECT + UPDATE + activity-log write each, which does not scale to+ # sources with thousands of schemas (e.g. a Slack workspace with thousands of+ # channels).+ deleted_at = datetime.now(UTC)+ ExternalDataSchema.objects.filter(team_id=self.team_id, id__in=[schema.id for schema in schemas]).update(+ deleted=True, deleted_at=deleted_at+ )+ # Mirror the bulk update onto the in-memory objects so the post-atomic+ # `schema.delete_table()` save() below doesn't overwrite deleted=True with the+ # stale in-memory value.+ for schema in schemas:+ schema.deleted = True+ schema.deleted_at = deleted_at++ # Clean up CDC companion tables (e.g. {name}_cdc) — these are standalone+ # DataWarehouseTable records linked to the source but not to schema.table.+ DataWarehouseTable.objects.filter(+ external_data_source_id=instance.id,+ team_id=self.team_id,+ deleted=False,+ ).exclude(id__in=[s.table_id for s in schemas if s.table_id is not None]).update(deleted=True)++ instance.soft_delete()++ # Best-effort webhook cleanup — soft-deletes are already committed+ source_type = ExternalDataSourceType(instance.source_type)+ source = base.SourceRegistry.get_source(source_type)+ if isinstance(source, WebhookSource) and instance.job_inputs:+ try:+ config = source.parse_config(instance.job_inputs)+ delete_webhook_and_hog_function(+ team=self.team,+ source=source,+ config=config,+ source_id=str(instance.pk),+ api_version=source.resolve_api_version(instance.api_version),+ )+ except Exception as e:+ base.capture_exception(e)++ # Best-effort external cleanup — soft-deletes are already committed+ latest_running_job = (+ ExternalDataJob.objects.filter(pipeline_id=instance.pk, team_id=instance.team_id)+ .order_by("-created_at")+ .first()+ )+ if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":+ base.cancel_external_data_workflow(latest_running_job.workflow_id)++ # Delete all schema sync schedules over a single shared Temporal connection — see+ # the matching comment in `create`. Guarded so a Temporal-connect failure here+ # doesn't skip the source/discovery schedule and S3 cleanup below.+ try:+ schedule_delete_errors = base.bulk_delete_external_data_schedules([str(schema.id) for schema in schemas])+ for schema_id, schedule_delete_error in schedule_delete_errors:+ base.capture_exception(schedule_delete_error, {"schema_id": schema_id})+ except Exception as e:+ base.capture_exception(e)++ for schema in schemas:+ try:+ schema.delete_table()+ except Exception as e:+ base.capture_exception(e)++ try:+ base.delete_external_data_schedule(str(instance.id))+ except Exception as e:+ base.capture_exception(e)++ try:+ base.delete_discover_schemas_schedule(str(instance.id))+ except Exception as e:+ base.capture_exception(e)++ return Response(status=status.HTTP_204_NO_CONTENT)++ @action(methods=["POST"], detail=True)+ def reload(self, request: Request, *args: Any, **kwargs: Any):+ instance: ExternalDataSource = self.get_object()++ if instance.is_direct_query:+ return self.refresh_schemas(request, *args, **kwargs)++ # Syncs every enabled schema, so it needs editor on each - a table locked below the source+ # would otherwise be refreshed here, and for a full refresh that drops and reloads it.+ self._assert_can_write_schemas(+ ExternalDataSchema.objects.filter(team_id=self.team_id, source_id=instance.id, should_sync=True)+ .exclude(deleted=True)+ .select_related("source", "table")+ )++ if is_any_external_data_schema_paused(self.team_id):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Monthly sync limit reached. Please increase your billing limit to resume syncing."},+ )++ try:+ base.trigger_external_data_source_workflow(instance)++ except temporalio.service.RPCError:+ # if the source schedule has been removed - trigger the schema schedules+ instance.reload_schemas()++ except Exception as e:+ base.logger.exception("Could not trigger external data job", exc_info=e)+ raise++ instance.status = "Running"+ instance.save()+ return Response(status=status.HTTP_200_OK)++ @extend_schema(+ request=SourceSetupSerializer,+ responses={201: SourceSetupResponseSerializer},+ )+ @action(methods=["POST"], detail=False)+ def setup(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """One-shot data warehouse source setup.++ Validate credentials, discover available tables, enable them all with sensible sync defaults+ (incremental where supported, else append, else full refresh), and create the source in a single+ call — the caller never has to assemble a `schemas` array. For sources that support webhooks+ (e.g. Stripe), a webhook is auto-registered after creation: on success webhook-capable tables+ switch to real-time webhook sync (unlocking webhook-only tables); on failure the polling+ defaults stay in place. For fine-grained table/sync control, use the lower-level+ `database_schema` + `create` flow instead.+ """+ # No database context needed here (unlike the read serializer), and skipping it avoids building+ # the HogQL Database on this hot path.+ serializer = SourceSetupSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ source_type = serializer.validated_data["source_type"]+ payload = dict(serializer.validated_data.get("payload") or {})++ secret_ref_response = credential_store._unresolved_secret_ref_response(payload)+ if secret_ref_response is not None:+ return secret_ref_response++ resolved = self._resolve_stored_credential(source_type, payload)+ if resolved.error_response is not None:+ return resolved.error_response+ # Mutable local: the CustomSource branch below rewrites payload keys before source creation.+ payload = resolved.payload++ source_type_model = ExternalDataSourceType(source_type)+ source = base.SourceRegistry.get_source(source_type_model)++ error_response, source_config = self._validate_source_config_and_credentials(source, source_type_model, payload)+ if error_response is not None or source_config is None:+ return error_response or Response(status=status.HTTP_400_BAD_REQUEST)++ if isinstance(source, CustomSource):+ # Validation may have adopted static OAuth2 secrets into an integration row and rewritten+ # the config to point at it. `_create_external_data_source` below re-parses the raw payload+ # (it skips the credential gate), so propagate the rewrite onto the payload — the created+ # source must store the row pointer, never the raw secrets.+ validated_payload = source_config.to_dict()+ for key in ("auth_oauth2_integration_id", "auth_oauth2_client_secret", "auth_oauth2_refresh_token"):+ if validated_payload.get(key):+ payload[key] = validated_payload[key]+ else:+ payload.pop(key, None)++ try:+ source_schemas = source.get_schemas(source_config, self.team_id)+ except NotImplementedError:+ # Source doesn't implement schema discovery (e.g. an unreleased source) so it can't be+ # set up via this one-shot flow — a caller mistake, not a server error worth capturing.+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers._source_unavailable_message(source_type)},+ )+ except Exception as e:+ # Credentials validated above can still fail here — `get_schemas` opens its own+ # connection — so classify via the source's non-retryable-error map, same as `create`,+ # `database_schema`, and `refresh_schemas`, instead of surfacing the raw driver error.+ error_message, is_expected_source_error = helpers._classify_refresh_schemas_error(source, e)+ if not is_expected_source_error:+ base.capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": error_message})++ if not source_schemas:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "No tables found for this source. Check the credentials and permissions."},+ )++ # Same best-effort per-table scope probe the schema picker runs, so one-shot setup doesn't+ # enable tables the credentials can only ever 403 on. Transient failure falls back to+ # "available", which is the pre-probe behavior.+ try:+ setup_permissions = source.get_endpoint_permissions(+ source_config, self.team_id, [schema.name for schema in source_schemas]+ )+ except Exception as e:+ base.capture_exception(e, {"source_type": source_type, "team_id": self.team_id})+ setup_permissions = {}++ # Some sources report a probe that couldn't run as a per-table reason rather than raising+ # (Stripe does this so the picker can render one row per failure). Setup has no such UI: a+ # blanket denial would silently create a source with every table off. Credentials that+ # genuinely read nothing are already rejected by validate_credentials above, so read+ # "everything denied" as an unreliable probe and keep the polling defaults.+ if setup_permissions and all(setup_permissions.get(schema.name) for schema in source_schemas):+ setup_permissions = {}++ # Build the schemas array server-side so the caller never has to. We've already validated+ # config + credentials above, so `_create_external_data_source` skips that second gate+ # (`skip_credential_validation`) to avoid a duplicate live credential round-trip.+ payload["schemas"] = build_default_schemas(source_schemas, permission_errors=setup_permissions)++ response = self._create_external_data_source(+ request,+ source_type=source_type,+ payload=payload,+ prefix=serializer.validated_data.get("prefix"),+ description=serializer.validated_data.get("description"),+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ created_via=ExternalDataSource.CreatedVia.MCP,+ direct_query_enabled=serializer.validated_data.get("direct_query_enabled", False),+ skip_credential_validation=True,+ )+ # Stored credentials are single-use: once the source owns them (in job_inputs), drop the stash.+ if resolved.credential is not None and response.status_code == status.HTTP_201_CREATED:+ resolved.credential.delete()++ if response.status_code == status.HTTP_201_CREATED and isinstance(source, WebhookSource):+ webhook_result = self._auto_register_webhook(+ source, source_config, str(response.data["id"]), source_schemas, permission_errors=setup_permissions+ )+ if webhook_result is not None:+ response.data["webhook"] = webhook_result+ return response++ @extend_schema(+ request=SourcePreviewRequestSerializer,+ responses={200: SourcePreviewResponseSerializer},+ )+ @action(methods=["POST"], detail=False)+ def preview_resource(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Read a bounded sample of rows for one resource of a Custom REST source.++ Lets a manifest author verify `data_selector`, `primary_key`, and the incremental+ `cursor_path` against live data before creating the source. Only `source_type: "Custom"`+ is supported — other source types return 400. The read is bounded (single page per+ resource, capped row count, short timeouts, no redirects). Manifest, validation, and SSRF+ problems return 400; a live fetch failure returns 200 with `error` set and empty `rows`.+ """+ serializer = SourcePreviewRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ source_type = serializer.validated_data["source_type"]+ source = base.SourceRegistry.get_source(ExternalDataSourceType(source_type))+ if not isinstance(source, CustomSource):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Preview is not supported for source type '{source_type}'."},+ )++ payload = dict(serializer.validated_data.get("payload") or {})+ is_valid, errors = source.validate_config(payload)+ if not is_valid:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid source config: {', '.join(errors)}"},+ )+ source_config = source.parse_config(payload)++ try:+ # preview_resource runs its own SSRF host check and bounded live read, so no+ # separate validate_credentials probe — the read is the credential check.+ result = source.preview_resource(+ cast(CustomSourceConfig, source_config),+ self.team_id,+ serializer.validated_data["resource_name"],+ serializer.validated_data["limit"],+ owner_user_id=self.request.user.id,+ )+ except ValueError as e:+ # ManifestValidationError (a ValueError) for manifest/graph/URL issues, or a plain+ # ValueError for an unknown resource_name / dependency cycle — all caller mistakes.+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})++ return Response(+ status=status.HTTP_200_OK,+ data=SourcePreviewResponseSerializer(+ {+ "rows": result.rows,+ "row_count": result.row_count,+ "columns": result.columns,+ "error": result.error,+ }+ ).data,+ )++ @extend_schema(+ request=DraftCustomManifestRequestSerializer,+ responses={200: DraftCustomManifestResponseSerializer},+ )+ @action(methods=["POST"], detail=False)+ def draft_custom_manifest(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Draft a Custom REST source manifest from API documentation using an LLM.++ Reads the docs (a URL fetched server-side, or pasted text / OpenAPI spec), asks the model to+ author a RESTAPIConfig manifest, and validates it against the create-path checks — repairing+ against validation errors up to a small budget. Returns the manifest for the user to review+ and tweak in the builder before creating the source; it does NOT create anything. Gated by the+ `dwh-custom-source-ai-builder` flag, and requires the org to have approved AI data processing,+ since the docs are sent to the LLM gateway.+ """+ # Gate on access (flag) then consent before validating input shape, so a caller without the+ # rollout or AI-data-processing opt-in is turned away before learning the request schema.+ if not is_custom_source_ai_builder_enabled_for_team(self.team):+ return Response(+ status=status.HTTP_404_NOT_FOUND,+ data={"message": "AI manifest drafting is not enabled for this organization."},+ )++ if self.team.organization.is_ai_data_processing_approved is not True:+ return Response(+ status=status.HTTP_403_FORBIDDEN,+ data={"message": "Enable AI data processing for this organization to use AI manifest drafting."},+ )++ serializer = DraftCustomManifestRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data++ docs_text = (data.get("docs_text") or "").strip()+ docs_source = "pasted_text" if docs_text else "fetched_url"+ if not docs_text:+ try:+ docs_text = fetch_docs_text(data["docs_url"])+ except DocsFetchError as e:+ return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": str(e)})++ try:+ result = draft_manifest_sync(+ team_id=self.team_id,+ source_name=data.get("source_name") or "",+ docs_text=docs_text,+ )+ except APIConnectionError as e:+ base.capture_exception(e, {"team_id": self.team_id})+ return Response(+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ data={+ "message": "Couldn't reach the AI service. If you're running locally, the LLM gateway isn't running — author the manifest manually instead."+ },+ )+ except Exception as e:+ base.capture_exception(e, {"team_id": self.team_id})+ return Response(+ status=status.HTTP_502_BAD_GATEWAY,+ data={"message": "The manifest drafting service failed. Try again, or author the manifest manually."},+ )++ # Success-path telemetry: this is a paid, unbilled-to-customer Opus path, so capture how it+ # performed (status, repair rounds, tables, where the docs came from) to drive a funnel from+ # draft → source created. No docs content or credentials — none are accepted here anymore.+ report_user_action(+ cast(User, request.user),+ "data warehouse custom source manifest drafted",+ {+ "draft_status": result.status,+ "attempts": result.attempts,+ "table_count": len(result.resource_names),+ "docs_source": docs_source,+ },+ team=self.team,+ request=request,+ )++ return Response(+ status=status.HTTP_200_OK,+ data=DraftCustomManifestResponseSerializer(+ {+ "draft_status": result.status,+ "manifest_json": result.manifest_json,+ "resource_names": result.resource_names,+ "attempts": result.attempts,+ "error": result.error,+ }+ ).data,+ )++ def _validate_source_config_and_credentials(+ self,+ source: AnySource,+ source_type_model: ExternalDataSourceType,+ payload: dict,+ access_method: str = ExternalDataSource.AccessMethod.WAREHOUSE,+ ) -> tuple[Response | None, Config | None]:+ """Run the config + live credential gate (including the SSRF host check) for a source payload."""+ if isinstance(source, CustomSource):+ # The OAuth2 integration row pointer is server-managed: validation derives it by adopting+ # the submitted auth_oauth2_* secrets into a row. Never trust a client-supplied pointer on+ # a pre-create seam — it could reference a row the caller shouldn't consume.+ payload.pop("auth_oauth2_integration_id", None)+ is_valid, errors = source.validate_config(payload)+ if not is_valid:+ return (+ Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid source config: {', '.join(errors)}"},+ ),+ None,+ )+ source_config: Config = source.parse_config(payload)++ try:+ if isinstance(source, (PostgresSource, MySQLSource)):+ credentials_valid, credentials_error = source.validate_credentials_for_access_method(+ cast(Any, source_config),+ self.team_id,+ access_method,+ require_ssl=new_source_requires_ssl(source_config),+ )+ elif isinstance(source, CustomSource):+ # Create-time validation for an integration-backed manifest may only use an unbound integration+ # owned by the requester, so the probe can't send another source's token to the submitted host.+ credentials_valid, credentials_error = source.validate_credentials(+ source_config, self.team_id, owner_user_id=self.request.user.id+ )+ else:+ credentials_valid, credentials_error = source.validate_credentials(source_config, self.team_id)+ except Exception as e:+ credentials_valid, credentials_error = helpers._credentials_validation_failed(source, self.team_id, e)+ if not credentials_valid:+ return (+ Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": credentials_error or helpers.INVALID_CREDENTIALS_FALLBACK_MESSAGE},+ ),+ None,+ )+ return None, source_config++ @action(methods=["POST"], detail=False)+ def source_prefix(self, request: Request, *arg: Any, **kwargs: Any):+ prefix = request.data.get("prefix", None)+ source_type = request.data["source_type"]+ access_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)++ if ExternalDataSource.is_system_managed_prefix(prefix):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers.RESERVED_SOURCE_NAME_MESSAGE},+ )++ if access_method == ExternalDataSource.AccessMethod.DIRECT:+ if source_type not in direct_capable_source_types():+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": helpers.DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE},+ )++ normalized_prefix = prefix.strip() if isinstance(prefix, str) else ""+ if not normalized_prefix:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Name is required for direct query sources"},+ )++ return Response(status=status.HTTP_200_OK)++ if not prefix:+ if self.prefix_required(source_type):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": "You already have a source of this type. Add a table prefix so this connection's tables don't clash with your existing source."+ },+ )+ elif self.prefix_exists(source_type, prefix):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Another source of this type already uses the prefix '{prefix}'. Choose a different prefix so this connection's tables don't clash."+ },+ )++ return Response(status=status.HTTP_200_OK)diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.py b/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.pynew file mode 100644index 000000000000..e6f444b5e18d--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/viewset.py@@ -0,0 +1,230 @@+"""External data source view set."""++from __future__ import annotations++from typing import Any, cast++from django.db.models import Prefetch++from drf_spectacular.utils import extend_schema+from opentelemetry import trace+from rest_framework import filters, serializers, viewsets+from rest_framework.exceptions import PermissionDenied+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.hogql.database.database import Database++from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.models.user import User+from posthog.permissions import AccessControlPermission, APIScopePermission, TeamMemberAccessPermission+from posthog.rate_limit import (+ CustomSourceAIBuilderBurstThrottle,+ CustomSourceAIBuilderDailyThrottle,+ CustomSourceAIBuilderSustainedThrottle,+)++from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin+from products.warehouse_sources.backend.facade.models import (+ ExternalDataSchema,+ ExternalDataSource,+ latest_completed_job_prefetch,+)++from . import credential_store, helpers, oauth_accounts, source_setup+from .change_data_capture import ExternalDataSourceCDCMixin+from .connection_options import ExternalDataSourceConnectionOptionsMixin+from .credential_store import ExternalDataSourceCredentialStoreMixin+from .job_runs import ExternalDataSourceJobRunsMixin+from .oauth_accounts import ExternalDataSourceOAuthAccountsMixin+from .schema_operations import ExternalDataSourceSchemaOperationsMixin+from .source_setup import ExternalDataSourceSetupMixin+from .webhook_setup import ExternalDataSourceWebhookSetupMixin+++@extend_schema(extensions={"x-product": "warehouse_sources"})+class ExternalDataSourceViewSet(+ ExternalDataSourceSetupMixin,+ ExternalDataSourceSchemaOperationsMixin,+ ExternalDataSourceCredentialStoreMixin,+ ExternalDataSourceOAuthAccountsMixin,+ ExternalDataSourceJobRunsMixin,+ ExternalDataSourceConnectionOptionsMixin,+ ExternalDataSourceWebhookSetupMixin,+ ExternalDataSourceCDCMixin,+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ viewsets.ModelViewSet,+):+ """+ Create, Read, Update and Delete External data Sources.+ """++ scope_object = "external_data_source"+ scope_object_write_actions = [+ "create",+ "update",+ "partial_update",+ "patch",+ "destroy",+ "reload",+ "refresh_schemas",+ "bulk_update_schemas",+ "database_schema",+ "setup",+ "store_credentials",+ "source_prefix",+ "revenue_analytics_config",+ "destinations",+ "create_webhook",+ "update_webhook_inputs",+ "delete_webhook",+ "check_cdc_prerequisites",+ "check_cdc_prerequisites_for_source",+ "enable_cdc",+ "disable_cdc",+ "repair_cdc",+ "update_cdc_settings",+ # Enumerates the connected provider's accounts/sites — write-scoped so a read-only token can't+ # list them (info disclosure); also gated behind admin in dangerously_get_permissions.+ "oauth_accounts",+ # Live outbound HTTP to a caller-supplied manifest (including POSTs) — a+ # side-effecting action, so it needs write scope, not read.+ "preview_resource",+ # Fetches a caller-supplied docs URL and calls the (paid) LLM gateway — side-effecting.+ "draft_custom_manifest",+ ]+ scope_object_read_actions = [+ "list",+ "retrieve",+ "jobs",+ "wizard",+ "connect_link",+ "stored_credentials",+ "webhook_info",+ "cdc_status",+ "direct_connection_options",+ ]+ queryset = ExternalDataSource.objects.all()+ serializer_class = source_setup.ExternalDataSourceSerializers+ filter_backends = [filters.SearchFilter]+ # `source_id` is an opaque internal connection UUID — useless to search by. Callers+ # (the in-app sources list, the MCP tool) narrow by what they can actually see: the+ # source type ("Stripe", "Postgres") and the HogQL table prefix.+ search_fields = ["source_type", "prefix"]+ ordering = "-created_at"++ def check_object_permissions(self, request: Request, obj: Any) -> None:+ super().check_object_permissions(request, obj)+ if request.method not in ("GET", "HEAD", "OPTIONS") and isinstance(obj, ExternalDataSource):+ if obj.is_system_managed:+ raise PermissionDenied("This source is managed by PostHog and cannot be changed through this API.")++ def dangerously_get_permissions(self):+ if self.action == "connections":+ return [+ IsAuthenticated(),+ APIScopePermission(),+ TeamMemberAccessPermission(),+ ]+ # The account picker enumerates every account/site the connected provider exposes, so require+ # manage access even though it's a GET — a read-only member shouldn't discover unrelated+ # accounts (info disclosure). Other actions fall back to the viewset defaults.+ if self.action == "oauth_accounts":+ return [+ IsAuthenticated(),+ APIScopePermission(),+ AccessControlPermission(),+ TeamMemberAccessPermission(),+ oauth_accounts.AccountPickerManagementPermission(),+ ]+ raise NotImplementedError()++ def get_throttles(self):+ # The AI manifest builder fans out to several Opus calls per request and isn't billed to the+ # customer, so cap it per team: a burst guard against double-submits/retries, an hourly window+ # for an intense setup session, and a daily backstop against scripted abuse.+ if self.action == "draft_custom_manifest":+ return [+ CustomSourceAIBuilderBurstThrottle(),+ CustomSourceAIBuilderSustainedThrottle(),+ CustomSourceAIBuilderDailyThrottle(),+ ]+ return super().get_throttles()++ def finalize_response(self, request: Request, response: Response, *args: Any, **kwargs: Any) -> Response:+ response = super().finalize_response(request, response, *args, **kwargs)+ # Tag the request span with the two things that drive source-list load cost — source count and+ # total serialized schema count — so the historically-slow list endpoint is diagnosable in+ # tracing. Done here rather than by overriding `list`, since a method named `list` would shadow+ # the builtin `list[...]` type used in annotations elsewhere in this class. Guarded for shape+ # because finalize_response also runs for error responses (no `results`) and other actions.+ if self.action == "list" and isinstance(response.data, dict):+ results = response.data.get("results")+ if isinstance(results, list):+ span = trace.get_current_span()+ span.set_attribute("data_warehouse.sources.count", len(results))+ span.set_attribute(+ "data_warehouse.sources.schemas.count",+ sum(len(source.get("schemas") or []) for source in results if isinstance(source, dict)),+ )+ return response++ def get_serializer_class(self) -> type[serializers.Serializer]:+ if self.action == "create":+ return source_setup.ExternalDataSourceCreateSerializer+ if self.action == "database_schema":+ return credential_store.DatabaseSchemaRequestSerializer+ return source_setup.ExternalDataSourceSerializers++ def get_serializer_context(self) -> dict[str, Any]:+ context = super().get_serializer_context()+ # Building the full HogQL Database and serializing per-schema table columns is expensive+ # and only needed when a caller reads `schemas[].table.columns` — which the source list view+ # never does (it only reads name/row_count). Gate both to single-source reads.+ include_columns = self.action != "list"+ context["include_columns"] = include_columns+ # The list serializes a trimmed per-schema shape; single-source reads serialize the full one.+ context["schemas_list_only"] = self.action == "list"+ if include_columns:+ context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))++ return context++ def safely_get_queryset(self, queryset):+ queryset = queryset.exclude(deleted=True)+ canonical_source = helpers._canonical_legacy_managed_warehouse_source(queryset.filter(team_id=self.team_id))+ queryset = helpers._hide_noncanonical_managed_warehouse_sources(queryset, canonical_source)++ # `table__credential` holds EncryptedTextField key material. The list never reads it (trimmed+ # schema shape, include_columns=False), so joining it across every schema — tens of thousands on+ # large sources — is pure waste there and is dropped. Every other action serializes columns+ # (include_columns=True), and building them reads `table.credential.access_key` per schema+ # (see DataWarehouseTable.hogql_definition), so keep the join off the list path only.+ schema_select = ["table__external_data_source"]+ if self.action != "list":+ schema_select.append("table__credential")++ return (+ queryset+ # created_by (FK) and revenue_analytics_config (reverse 1:1) are read per source during+ # serialization. select_related folds them into the main query instead of firing one+ # extra SELECT per source — the reverse 1:1 was an unprefetched N+1 that dominated the+ # list load (up to one query, and a get_or_create write, per source).+ .select_related("created_by", "revenue_analytics_config")+ .prefetch_related(+ latest_completed_job_prefetch(self.team_id, "jobs", to_attr="ordered_jobs"),+ # The one place schemas are read during serialization. `active_schemas` used to be a+ # second prefetch over the same rows — it's now derived in Python from this one (see+ # `_active_schemas`), so the schema table is scanned once.+ Prefetch(+ "schemas",+ queryset=ExternalDataSchema.objects.filter(team_id=self.team_id)+ .exclude(deleted=True)+ .select_related(*schema_select)+ .order_by("name"),+ ),+ )+ .order_by(self.ordering)+ )diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.pynew file mode 100644index 000000000000..5a1f4a8cab1b--- /dev/null+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/webhook_setup.py@@ -0,0 +1,684 @@+"""Serializers and endpoints for webhook setup."""++from __future__ import annotations++import dataclasses+from collections.abc import Mapping+from typing import Any++from drf_spectacular.utils import extend_schema+from rest_framework import serializers, status+from rest_framework.exceptions import ValidationError+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.utils import action+from posthog.cdp.validation import InputsSerializer++from products.cdp.backend.facade.api import HogFunctionSerializer+from products.cdp.backend.facade.models import HogFunction+from products.data_warehouse.backend.facade.api import (+ create_and_register_webhook,+ delete_webhook_and_hog_function,+ get_or_create_webhook_hog_function,+ get_webhook_url,+ sync_external_data_job_workflow,+)+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.source_management import (+ Config,+ ExternalWebhookInfo,+ SourceSchema,+ WebhookSource,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++from . import base+++class SourceSetupWebhookSerializer(serializers.Serializer):+ success = serializers.BooleanField(+ help_text=(+ "Whether the webhook was registered with the external service. When true, webhook-capable tables "+ "(including webhook-only ones) sync via real-time webhooks; when false, tables fall back to the "+ "polling sync defaults and webhook-only tables stay disabled."+ )+ )+ webhook_url = serializers.CharField(+ allow_null=True, help_text="The PostHog endpoint the external service delivers events to."+ )+ error = serializers.CharField(+ allow_null=True, help_text="Why webhook registration failed (e.g. the credentials lack webhook permissions)."+ )+ pending_inputs = serializers.ListField(+ child=serializers.CharField(),+ help_text=(+ "Webhook input names the user still needs to provide (e.g. a signing secret the external API did not "+ "return on create). Submit them via the update_webhook_inputs endpoint."+ ),+ )+++class WebhookHogFunctionSerializer(serializers.Serializer):+ id = serializers.CharField(help_text="ID of the webhook delivery hog function.")+ name = serializers.CharField(help_text="Name of the webhook delivery hog function.")+ enabled = serializers.BooleanField(help_text="Whether the webhook delivery function is enabled.")+ created_at = serializers.CharField(help_text="When the webhook delivery function was created (ISO 8601).")+ status = serializers.DictField(+ child=serializers.JSONField(),+ help_text="Delivery health reported by the pipeline: `state` and `tokens` counters.",+ )+++class WebhookExternalStatusSerializer(serializers.Serializer):+ exists = serializers.BooleanField(help_text="Whether the webhook exists on the external service.")+ url = serializers.CharField(allow_null=True, allow_blank=True, help_text="The webhook URL on the external service.")+ enabled_events = serializers.ListField(+ child=serializers.CharField(), allow_null=True, help_text="Events the external webhook is subscribed to."+ )+ status = serializers.CharField(+ allow_null=True,+ allow_blank=True,+ help_text="Delivery health as the external service reports it (e.g. 'enabled').",+ )+ description = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="Description the external service holds for it."+ )+ created_at = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="When the external webhook was created."+ )+ api_version = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="Vendor API version the endpoint delivers at, when pinned."+ )+ error = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="Read error the external service returned, if any."+ )+++class WebhookInfoResponseSerializer(serializers.Serializer):+ supports_webhooks = serializers.BooleanField(+ help_text="Whether the source type supports webhooks at all. When false, the other fields are absent."+ )+ exists = serializers.BooleanField(+ help_text="Whether a PostHog webhook delivery function exists for this source yet."+ )+ auto_creation_blocked_reason = serializers.CharField(+ allow_null=True,+ help_text=(+ "Set when the connection's credentials can never create the webhook, so only manual setup is left. "+ "Null means 'not known to be blocked'."+ ),+ )+ hog_function = WebhookHogFunctionSerializer(+ allow_null=True, help_text="The webhook delivery function, present once the webhook exists."+ )+ webhook_url = serializers.CharField(+ allow_null=True, help_text="The PostHog endpoint the external service delivers events to."+ )+ schema_mapping = serializers.DictField(+ child=serializers.CharField(),+ help_text="Resource name to external schema id, as configured on the webhook function.",+ )+ inputs = InputsSerializer(+ required=False,+ help_text="Current webhook function inputs keyed by the source's declared webhook field names.",+ )+ external_status = WebhookExternalStatusSerializer(+ allow_null=True, help_text="Live webhook state as the external service reports it, when it could be read."+ )+ missing_events = serializers.ListField(+ required=False,+ child=serializers.CharField(),+ help_text="Desired provider events not yet on the webhook (manual setup, or created before a new table).",+ )+++class WebhookInfoBlockedResponseSerializer(serializers.Serializer):+ supports_webhooks = serializers.BooleanField(help_text="Whether the source type supports webhooks. True here.")+ exists = serializers.BooleanField(help_text="Always false: no webhook function exists yet.")+ auto_creation_blocked_reason = serializers.CharField(+ help_text="Why automatic creation can't proceed, so only manual setup is left."+ )+++class CreateWebhookResponseSerializer(serializers.Serializer):+ success = serializers.BooleanField(help_text="Whether the webhook was created and registered with the source.")+ webhook_url = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="The PostHog endpoint the external service delivers events to."+ )+ error = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="Why creation failed, when success is false."+ )+ pending_inputs = serializers.ListField(+ child=serializers.CharField(),+ help_text="Inputs the external service needs before delivery works. Submit via update_webhook_inputs.",+ )+++class UpdateWebhookInputsResponseSerializer(serializers.Serializer):+ success = serializers.BooleanField(help_text="Whether the inputs were saved and pushed to the external service.")+++class DeleteWebhookResponseSerializer(serializers.Serializer):+ success = serializers.BooleanField(help_text="Whether the webhook delivery function was deleted.")+ external_deleted = serializers.BooleanField(+ help_text=(+ "Whether the webhook was also removed from the external service. False when the source config was "+ "already gone and only the local function was cleaned up, or when the external call failed."+ )+ )+ error = serializers.CharField(+ allow_null=True, allow_blank=True, help_text="Why the external deletion failed, when external_deleted is false."+ )+++class ExternalDataSourceWebhookSetupMixin(base.ExternalDataSourceViewSetBase):+ def _auto_register_webhook(+ self,+ source: WebhookSource,+ source_config: Config,+ source_id: str,+ source_schemas: list[SourceSchema],+ permission_errors: Mapping[str, str | None] | None = None,+ ) -> dict | None:+ """Best-effort webhook auto-registration for one-shot setup.++ The source was just created with polling sync defaults (webhook-only tables disabled). If the+ source supports webhook auto-creation and the credentials allow it, register the webhook and+ switch every webhook-capable table to the webhook sync method — unlocking webhook-only tables.+ Failure never breaks setup: the polling defaults stay in place and webhook-only tables remain+ disabled, exactly as if the source didn't support webhooks.+ """+ # Tables marked `should_sync_default=False` need explicit opt-in even when webhook-capable —+ # one-shot setup must not force-enable what the schema picker would leave off (the same+ # contract `build_default_schemas` honors). A table the credentials can't read is excluded+ # for the same reason: a webhook can't deliver rows the connection was denied.+ denied = {name for name, reason in (permission_errors or {}).items() if reason}+ webhook_capable = {+ s.name for s in source_schemas if s.supports_webhooks and s.should_sync_default and s.name not in denied+ }+ if not webhook_capable or source.webhook_template is None:+ return None++ instance = ExternalDataSource.objects.get(pk=source_id, team_id=self.team_id)+ # Registration can't succeed on a connection whose grants exclude webhook management, and+ # one-shot setup has no manual-fallback UI to fall back into: leave the polling defaults.+ blocked_reason = self._webhook_creation_blocked_reason(source, instance)+ if blocked_reason is not None:+ return {"success": False, "webhook_url": None, "error": blocked_reason, "pending_inputs": []}++ eligible_schemas = list(+ ExternalDataSchema.objects.filter(source=instance, team_id=self.team_id, name__in=webhook_capable).exclude(+ deleted=True+ )+ )+ if not eligible_schemas:+ return None++ def failure(error: str | None) -> dict:+ return {"success": False, "webhook_url": None, "error": error, "pending_inputs": []}++ try:+ hog_fn_result = get_or_create_webhook_hog_function(+ team=self.team,+ source=source,+ source_id=str(instance.pk),+ eligible_schemas=eligible_schemas,+ config=source_config,+ )+ if hog_fn_result.error or hog_fn_result.hog_function_id is None:+ return failure(hog_fn_result.error)++ registration = create_and_register_webhook(+ source,+ source_config,+ hog_fn_result,+ self.team_id,+ api_version=source.resolve_api_version(instance.api_version),+ )+ except Exception as e:+ base.capture_exception(e, {"source_id": source_id, "team_id": self.team_id})+ return failure(str(e))++ if not registration.success:+ # The external registration failed (e.g. credentials can't create webhooks), so the+ # handler would never receive events — remove it and keep the polling defaults.+ hog_function = HogFunction.objects.get(id=hog_fn_result.hog_function_id, team_id=self.team_id)+ hog_function.deleted = True+ hog_function.enabled = False+ hog_function.save(update_fields=["deleted", "enabled"])+ return failure(registration.error)++ for schema in eligible_schemas:+ newly_enabled = not schema.should_sync+ schema.sync_type = ExternalDataSchema.SyncType.WEBHOOK+ schema.should_sync = True+ schema.save(update_fields=["sync_type", "should_sync"])+ if newly_enabled:+ # Webhook-only tables were created disabled, so no sync schedule exists yet. The+ # schedule still matters for webhook schemas: it ingests the buffered webhook events.+ try:+ sync_external_data_job_workflow(schema, create=True)+ except Exception as e:+ base.logger.exception(+ "Could not create sync schedule for webhook schema", exc_info=e, schema_id=str(schema.id)+ )++ return {+ "success": True,+ "webhook_url": registration.webhook_url,+ "error": None,+ "pending_inputs": list(registration.pending_inputs),+ }++ def _compute_missing_webhook_events(+ self,+ source: WebhookSource,+ config: Any,+ instance: ExternalDataSource,+ external_status: ExternalWebhookInfo | None,+ ) -> list[str]:+ """Desired events not yet on the provider webhook — surfaced so manual-webhook users+ (or keys lacking webhook-write scope) know what to add."""+ if not external_status or not external_status.exists or external_status.error:+ return []++ eligible_schema_names = list(+ ExternalDataSchema.objects.filter(+ source=instance,+ team_id=self.team_id,+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ should_sync=True,+ )+ .exclude(deleted=True)+ .values_list("name", flat=True)+ )++ desired = source.get_desired_webhook_events(config, eligible_schema_names)+ if not desired:+ return []++ current = set(external_status.enabled_events or [])+ if "*" in current:+ return []++ return sorted(e for e in desired if e not in current)++ def _webhook_creation_blocked_reason(self, source: WebhookSource, instance: ExternalDataSource) -> str | None:+ """Ask the source whether this connection can never create the provider-side webhook.+ Best-effort: an unparseable config or a source-side failure leaves the button offered,+ which is the behavior before the check existed."""+ if not instance.job_inputs:+ return None+ try:+ return source.webhook_creation_blocked_reason(source.parse_config(instance.job_inputs), self.team_id)+ except Exception as e:+ base.capture_exception(e)+ return None++ @extend_schema(responses=WebhookInfoResponseSerializer)+ @action(methods=["GET"], detail=True)+ def webhook_info(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance: ExternalDataSource = self.get_object()+ source_type = ExternalDataSourceType(instance.source_type)+ source = base.SourceRegistry.get_source(source_type)++ if not isinstance(source, WebhookSource):+ return Response(+ status=status.HTTP_200_OK,+ data=WebhookInfoResponseSerializer(+ {+ "supports_webhooks": False,+ "exists": False,+ "auto_creation_blocked_reason": None,+ "hog_function": None,+ "webhook_url": None,+ "schema_mapping": {},+ "external_status": None,+ }+ ).data,+ )++ blocked_reason = self._webhook_creation_blocked_reason(source, instance)++ hog_function = HogFunction.objects.filter(+ team=self.team,+ type="warehouse_source_webhook",+ inputs__source_id__value=str(instance.pk),+ deleted=False,+ ).first()++ if not hog_function:+ return Response(+ status=status.HTTP_200_OK,+ data=WebhookInfoResponseSerializer(+ {+ "supports_webhooks": True,+ "exists": False,+ "auto_creation_blocked_reason": blocked_reason,+ "hog_function": None,+ "webhook_url": None,+ "schema_mapping": {},+ "inputs": {},+ "external_status": None,+ "missing_events": [],+ }+ ).data,+ )++ webhook_url = get_webhook_url(hog_function.id)++ external_status: ExternalWebhookInfo | None = None+ missing_events: list[str] = []++ if instance.job_inputs:+ try:+ config = source.parse_config(instance.job_inputs)+ external_status = source.get_external_webhook_info(+ config, webhook_url, self.team_id, api_version=source.resolve_api_version(instance.api_version)+ )+ missing_events = self._compute_missing_webhook_events(source, config, instance, external_status)+ except Exception as e:+ base.capture_exception(e)++ schema_mapping = {}+ if hog_function.inputs:+ schema_mapping = hog_function.inputs.get("schema_mapping", {}).get("value", {})++ webhook_field_names = {f.name for f in (source.get_source_config.webhookFields or [])}+ all_inputs = HogFunctionSerializer(hog_function).data.get("inputs") or {}+ webhook_inputs = {k: v for k, v in all_inputs.items() if k in webhook_field_names}++ return Response(+ status=status.HTTP_200_OK,+ data=WebhookInfoResponseSerializer(+ {+ "supports_webhooks": True,+ "exists": True,+ "auto_creation_blocked_reason": blocked_reason,+ "hog_function": {+ "id": str(hog_function.id),+ "name": hog_function.name,+ "enabled": hog_function.enabled,+ "created_at": hog_function.created_at.isoformat(),+ "status": hog_function.status,+ },+ "webhook_url": webhook_url,+ "schema_mapping": schema_mapping,+ "inputs": webhook_inputs,+ "external_status": dataclasses.asdict(external_status) if external_status else None,+ "missing_events": missing_events,+ }+ ).data,+ )++ @extend_schema(responses=CreateWebhookResponseSerializer)+ @action(methods=["POST"], detail=True)+ def create_webhook(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance: ExternalDataSource = self.get_object()++ if not instance.job_inputs:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Source has no configuration"},+ )++ source_type = ExternalDataSourceType(instance.source_type)+ source = base.SourceRegistry.get_source(source_type)++ if not isinstance(source, WebhookSource):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "This source type does not support webhooks"},+ )++ # A connection known to lack the grant can't be fixed by trying. The hog function is still+ # minted below so manual setup has a URL to paste; only the doomed provider round-trip (one+ # call per repository, for GitHub) is skipped.+ blocked_reason = self._webhook_creation_blocked_reason(source, instance)++ effective_api_version = source.resolve_api_version(instance.api_version)+ try:+ config = source.parse_config(instance.job_inputs)+ source_schemas = source.get_schemas(config, self.team_id, api_version=effective_api_version)+ except ValidationError as e:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Invalid source configuration", "details": getattr(e, "detail", str(e))},+ )+ except Exception as e:+ base.capture_exception(e)+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Failed to load source configuration or schemas"},+ )++ webhook_source_schemas = {s.name: s for s in source_schemas if s.supports_webhooks}++ db_schemas = ExternalDataSchema.objects.filter(+ source=instance,+ team_id=self.team_id,+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ should_sync=True,+ ).exclude(deleted=True)++ eligible_schemas = [s for s in db_schemas if s.name in webhook_source_schemas]++ hog_fn_result = get_or_create_webhook_hog_function(+ team=self.team,+ source=source,+ source_id=str(instance.pk),+ eligible_schemas=eligible_schemas,+ config=config,+ )++ if hog_fn_result.error:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": hog_fn_result.error},+ )++ if blocked_reason is not None:+ return Response(+ status=status.HTTP_200_OK,+ data=CreateWebhookResponseSerializer(+ {+ "success": False,+ "webhook_url": hog_fn_result.webhook_url,+ "error": blocked_reason,+ "pending_inputs": [],+ }+ ).data,+ )++ result = create_and_register_webhook(+ source, config, hog_fn_result, self.team_id, api_version=effective_api_version+ )++ return Response(+ status=status.HTTP_200_OK,+ data=CreateWebhookResponseSerializer(+ {+ "success": result.success,+ "webhook_url": result.webhook_url,+ "error": result.error,+ "pending_inputs": result.pending_inputs,+ }+ ).data,+ )++ @extend_schema(responses=UpdateWebhookInputsResponseSerializer)+ @action(methods=["POST"], detail=True)+ def update_webhook_inputs(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance: ExternalDataSource = self.get_object()++ if not instance.job_inputs:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Source has no configuration"},+ )++ source_type = ExternalDataSourceType(instance.source_type)+ source = base.SourceRegistry.get_source(source_type)++ if not isinstance(source, WebhookSource):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "This source type does not support webhooks"},+ )++ inputs = request.data.get("inputs", {})+ if not inputs or not isinstance(inputs, dict):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "No inputs provided"},+ )++ source_config = source.get_source_config+ webhook_fields = source_config.webhookFields or []+ webhook_field_names = {f.name for f in webhook_fields}++ invalid_keys = set(inputs.keys()) - webhook_field_names+ if invalid_keys:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Invalid input keys: {', '.join(invalid_keys)}"},+ )++ required_fields = [f.name for f in webhook_fields if getattr(f, "required", False)]+ blanked_required = [name for name in required_fields if name in inputs and not inputs[name]]+ if blanked_required:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": f"Missing required fields: {', '.join(blanked_required)}"},+ )++ try:+ hog_function = HogFunction.objects.get(+ team=self.team,+ type="warehouse_source_webhook",+ inputs__source_id__value=str(instance.pk),+ deleted=False,+ )+ except HogFunction.DoesNotExist:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "No webhook function found for this source. Create a webhook first."},+ )++ try:+ config = source.parse_config(instance.job_inputs)+ except ValidationError as e:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Invalid source configuration", "details": getattr(e, "detail", str(e))},+ )+ except Exception as e:+ base.capture_exception(e)+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Failed to load source configuration"},+ )++ assert hog_function.inputs is not None+ hog_function.inputs = {+ **hog_function.inputs,+ **{key: {"value": value} for key, value in inputs.items()},+ }+ hog_function.save(update_fields=["inputs", "encrypted_inputs"])++ success, error = source.webhook_inputs_updated(+ config,+ get_webhook_url(hog_function.id),+ self.team.pk,+ inputs,+ api_version=source.resolve_api_version(instance.api_version),+ )+ if not success:+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"success": False, "error": error or "Failed to update webhook on the external source."},+ )++ return Response(status=status.HTTP_200_OK, data=UpdateWebhookInputsResponseSerializer({"success": True}).data)++ @extend_schema(responses=DeleteWebhookResponseSerializer)+ @action(methods=["POST"], detail=True)+ def delete_webhook(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance: ExternalDataSource = self.get_object()++ source_type = ExternalDataSourceType(instance.source_type)+ source = base.SourceRegistry.get_source(source_type)++ if not isinstance(source, WebhookSource):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "This source type does not support webhooks"},+ )++ # Check that no schemas are still relying on the webhook — deleting it+ # would break their sync pipeline.+ webhook_schemas = ExternalDataSchema.objects.filter(+ source=instance,+ team_id=self.team_id,+ sync_type=ExternalDataSchema.SyncType.WEBHOOK,+ should_sync=True,+ ).exclude(deleted=True)++ if webhook_schemas.exists():+ schema_names = list(webhook_schemas.values_list("name", flat=True))+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={+ "message": f"Cannot delete webhook while tables are using webhook sync: {', '.join(schema_names)}. Switch them to full refresh, incremental, or disable syncing first.",+ },+ )++ if not instance.job_inputs:+ # No config means we can't call the external API, but we can still+ # clean up the HogFunction.+ try:+ hog_function = HogFunction.objects.get(+ team=self.team,+ type="warehouse_source_webhook",+ inputs__source_id__value=str(instance.pk),+ deleted=False,+ )+ hog_function.deleted = True+ hog_function.enabled = False+ hog_function.save(update_fields=["deleted", "enabled"])+ except HogFunction.DoesNotExist:+ pass++ return Response(+ status=status.HTTP_200_OK,+ data=DeleteWebhookResponseSerializer({"success": True, "external_deleted": False}).data,+ )++ try:+ config = source.parse_config(instance.job_inputs)+ except Exception as e:+ base.capture_exception(e)+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "Failed to parse source configuration"},+ )++ result = delete_webhook_and_hog_function(+ team=self.team,+ source=source,+ config=config,+ source_id=str(instance.pk),+ api_version=source.resolve_api_version(instance.api_version),+ )++ return Response(+ status=status.HTTP_200_OK,+ data=DeleteWebhookResponseSerializer(+ {+ "success": result.success,+ "external_deleted": result.external_deleted,+ "error": result.error,+ }+ ).data,+ )diff --git a/products/warehouse_sources/backend/routes.py b/products/warehouse_sources/backend/routes.pyindex 526e601889cb..8991e28f526f 100644--- a/products/warehouse_sources/backend/routes.py+++ b/products/warehouse_sources/backend/routes.py@@ -4,14 +4,14 @@ from products.warehouse_sources.backend.presentation.views import (column_statistics,external_data_destination,external_data_schema,- external_data_source,)+from products.warehouse_sources.backend.presentation.views.external_data_source.viewset import ExternalDataSourceViewSetdef register_routes(routers: RouterRegistry) -> None:routers.projects.register(r"external_data_sources",- external_data_source.ExternalDataSourceViewSet,+ ExternalDataSourceViewSet,"project_external_data_sources",["team_id"],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.pyindex 64f55abf3e23..d7d0ecaefd06 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/tests/test_trino.py@@ -5,7 +5,9 @@ from unittest.mock import MagicMock, patchfrom trino.exceptions import TrinoExternalError-from products.warehouse_sources.backend.presentation.views.external_data_source import _classify_refresh_schemas_error+from products.warehouse_sources.backend.presentation.views.external_data_source.helpers import (+ _classify_refresh_schemas_error,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.trino import (TrinoAuthTypeConfig,TrinoSourceConfig,diff --git a/products/warehouse_sources/backend/tests/api/test_draft_custom_manifest.py b/products/warehouse_sources/backend/tests/api/test_draft_custom_manifest.pyindex 36cdd52f7de9..f010eef21c59 100644--- a/products/warehouse_sources/backend/tests/api/test_draft_custom_manifest.py+++ b/products/warehouse_sources/backend/tests/api/test_draft_custom_manifest.py@@ -12,9 +12,11 @@ from posthog.models import Teamfrom products.warehouse_sources.backend.temporal.data_imports.sources.custom.ai_builder import ManifestDraftResult-_DRAFT_PATH = "products.warehouse_sources.backend.presentation.views.external_data_source.draft_manifest_sync"-_FETCH_PATH = "products.warehouse_sources.backend.presentation.views.external_data_source.fetch_docs_text"-_FLAG_PATH = "products.warehouse_sources.backend.presentation.views.external_data_source.is_custom_source_ai_builder_enabled_for_team"+_DRAFT_PATH = (+ "products.warehouse_sources.backend.presentation.views.external_data_source.source_setup.draft_manifest_sync"+)+_FETCH_PATH = "products.warehouse_sources.backend.presentation.views.external_data_source.source_setup.fetch_docs_text"+_FLAG_PATH = "products.warehouse_sources.backend.presentation.views.external_data_source.source_setup.is_custom_source_ai_builder_enabled_for_team"_THROTTLE_SCOPES = ("custom_source_ai_builder_burst","custom_source_ai_builder_sustained",diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 6d50675c9a0b..31365b973ef2 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -61,10 +61,9 @@ from products.warehouse_sources.backend.models.external_data_destination importExternalDataSourceDestination,)from products.warehouse_sources.backend.presentation.views.external_data_schema import ExternalDataSchemaSerializer-from products.warehouse_sources.backend.presentation.views.external_data_source import (+from products.warehouse_sources.backend.presentation.views.external_data_source.helpers import (DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE,INVALID_CREDENTIALS_FALLBACK_MESSAGE,- ExternalDataSourceViewSet,_classify_refresh_schemas_error,get_declared_field_names,get_direct_connection_metadata,@@ -74,6 +73,7 @@ from products.warehouse_sources.backend.presentation.views.external_data_sourcerestore_declared_field_names,strip_sensitive_from_dict,)+from products.warehouse_sources.backend.presentation.views.external_data_source.viewset import ExternalDataSourceViewSetfrom products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.bigquery.bigquery import BigQuerySourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (@@ -369,7 +369,7 @@ class TestExternalDataSource(APIBaseTest):return []with patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.bulk_create_external_data_job_schedules",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.bulk_create_external_data_job_schedules",side_effect=record_links,):response = self.client.post(@@ -537,7 +537,9 @@ class TestExternalDataSource(APIBaseTest):assert "not supported for this source type" in str(response.json())assert not ExternalDataSource.objects.filter(team_id=self.team.pk).exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.sync_discover_schemas_schedule")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.sync_discover_schemas_schedule"+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",return_value=(True, None),@@ -564,8 +566,10 @@ class TestExternalDataSource(APIBaseTest):created_source = mock_sync_discover.call_args.args[0]assert str(created_source.id) == response.json()["id"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.sync_discover_schemas_schedule")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.sync_discover_schemas_schedule"+ )+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_direct_query_source_skips_discovery_schedule(self, mock_get_source, mock_sync_discover):_configure_source_mock_versioning(mock_get_source)# Direct-query sources resolve schemas at query time and opt out of all@@ -1432,7 +1436,9 @@ class TestExternalDataSource(APIBaseTest):"products.warehouse_sources.backend.presentation.views.external_data_schema.sync_external_data_job_workflow",side_effect=Exception("temporal unavailable"),),- patch("products.warehouse_sources.backend.presentation.views.external_data_source.logger") as mock_logger,+ patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.logger"+ ) as mock_logger,):try:response = self.client.patch(@@ -1725,7 +1731,7 @@ class TestExternalDataSource(APIBaseTest):"products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",return_value=False,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")def test_bulk_update_schemas_apply_sync_defaults_skips_capture_for_expected_errors(self, _name, raised_exception, should_capture, mock_capture_exception, _mock_workflow_exists):@@ -2440,7 +2446,7 @@ class TestExternalDataSource(APIBaseTest):assert "'private_key'" in response.json()["message"]assert "'private_key_id'" in response.json()["message"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")def test_create_external_data_source_bigquery_returns_400_on_credentials_rejected_during_schema_discovery(self, mock_capture_exception):@@ -3171,7 +3177,7 @@ class TestExternalDataSource(APIBaseTest):assert ExternalDataSchema.objects.filter(pk=schema.pk, deleted=True).exists()@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.delete_discover_schemas_schedule"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.delete_discover_schemas_schedule")def test_delete_external_data_source_tears_down_discovery_schedule(self, mock_delete_discover):source = self._create_external_data_source()@@ -3182,13 +3188,13 @@ class TestExternalDataSource(APIBaseTest):assert response.status_code == 204mock_delete_discover.assert_called_once_with(str(source.pk))- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.bulk_delete_external_data_schedules",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.bulk_delete_external_data_schedules",return_value=[("schema-id", Exception("Schema schedule delete failed"))],)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.delete_external_data_schedule",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.delete_external_data_schedule",side_effect=Exception("External delete failed"),)def test_delete_external_data_source_soft_deletes_even_if_external_cleanup_fails(@@ -3216,7 +3222,7 @@ class TestExternalDataSource(APIBaseTest):# TODO: update this test@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.trigger_external_data_source_workflow")def test_reload_external_data_source(self, mock_trigger):source = self._create_external_data_source()@@ -3229,7 +3235,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, 200)self.assertEqual(source.status, "Running")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_creates_new_schemas_and_returns_counts(self, mock_get_source):parsed_config = Mock(spec=["to_dict"])parsed_config.to_dict.return_value = {@@ -3267,7 +3273,7 @@ class TestExternalDataSource(APIBaseTest):)self.assertCountEqual(names, ["table_a", "table_b"])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_system_managed_source_rejects_schema_refresh(self, mock_get_source):source = self._create_external_data_source()source.connection_metadata = {"system_managed": True}@@ -3301,7 +3307,7 @@ class TestExternalDataSource(APIBaseTest):assert schema.should_sync is False@patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_auto_enables_matching_new_schemas(self, mock_get_source, mock_schedule):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3384,7 +3390,7 @@ class TestExternalDataSource(APIBaseTest):source.refresh_from_db()self.assertFalse(source.auto_sync_new_schemas)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_creates_new_schemas_and_deletes_missing_schemas(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3414,7 +3420,7 @@ class TestExternalDataSource(APIBaseTest):)self.assertCountEqual(names, ["new_table"])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_adds_only_new_schemas(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3441,7 +3447,7 @@ class TestExternalDataSource(APIBaseTest):).exists())- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_idempotent_no_duplicates(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3463,7 +3469,7 @@ class TestExternalDataSource(APIBaseTest):1,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_restores_deleted_schema_instead_of_creating_duplicate(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3510,7 +3516,7 @@ class TestExternalDataSource(APIBaseTest):self.assertFalse(restored_schema.should_sync)self.assertEqual(restored_schema.sync_type_config.get("legacy_key"), "keep")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_updates_labels_on_existing_schemas(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3529,7 +3535,7 @@ class TestExternalDataSource(APIBaseTest):schema.refresh_from_db()self.assertEqual(schema.label, "general")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_updates_changed_label(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3548,7 +3554,7 @@ class TestExternalDataSource(APIBaseTest):schema.refresh_from_db()self.assertEqual(schema.label, "renamed-channel")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_sets_label_on_new_schema(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3564,7 +3570,7 @@ class TestExternalDataSource(APIBaseTest):schema = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="c456")self.assertEqual(schema.label, "random")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_sets_label_on_restored_deleted_schema(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3596,7 +3602,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, 400)self.assertIn("configuration", response.json().get("message", ""))- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_returns_400_when_get_schemas_raises(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_non_retryable_errors.return_value = {"Connection failed": None}@@ -3610,7 +3616,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, 400)self.assertIn("Could not fetch schemas from source", response.json().get("message", ""))- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_returns_zero_total_tables_seen_when_source_returns_nothing(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = []@@ -3626,8 +3632,8 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(data["deleted"], 0)self.assertEqual(data["total_tables_seen"], 0)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_returns_specific_message_without_capture_for_expected_source_error(self, mock_get_source, mock_capture_exception):@@ -3647,8 +3653,8 @@ class TestExternalDataSource(APIBaseTest):)mock_capture_exception.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_captures_unexpected_source_error(self, mock_get_source, mock_capture_exception):error = RuntimeError("schema parser exploded")mock_get_source.return_value.parse_config.return_value = None@@ -3672,9 +3678,9 @@ class TestExternalDataSource(APIBaseTest):},)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.trigger_external_data_source_workflow")def test_reload_direct_external_data_source_refreshes_schemas(self, mock_trigger, mock_get_source):mock_get_source.return_value.parse_config.return_value = None@@ -3723,7 +3729,7 @@ class TestExternalDataSource(APIBaseTest):[{"column": "user_id", "target_table": "posthog_user", "target_column": "id"}],)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_direct_postgres_soft_deletes_live_tables_for_deleted_schemas(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = []@@ -3763,7 +3769,7 @@ class TestExternalDataSource(APIBaseTest):self.assertTrue(DataWarehouseTable.raw_objects.filter(pk=table.pk, deleted=True).exists())self.assertTrue(ExternalDataSchema.objects.filter(pk=stale_schema.pk, deleted=True).exists())- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_direct_postgres_keeps_disabled_schema_table_deleted(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3814,7 +3820,7 @@ class TestExternalDataSource(APIBaseTest):self.assertTrue(DataWarehouseTable.raw_objects.get(pk=table.pk).deleted)self.assertEqual(schema.sync_type_config["schema_metadata"]["columns"][0]["name"], "id")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_direct_postgres_new_schema_is_opt_in(self, mock_get_source):mock_get_source.return_value.parse_config.return_value = Nonemock_get_source.return_value.get_schemas.return_value = [@@ -3847,7 +3853,7 @@ class TestExternalDataSource(APIBaseTest):self.assertFalse(schema.should_sync)self.assertIsNone(schema.table)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_direct_postgres_preserves_disabled_schema_when_it_reappears(self, mock_get_source):source = ExternalDataSource.objects.create(team_id=self.team.pk,@@ -3897,7 +3903,7 @@ class TestExternalDataSource(APIBaseTest):self.assertFalse(schema.should_sync)self.assertIsNone(schema.table)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_direct_postgres_preserves_enabled_schema_when_it_reappears(self, mock_get_source):source = ExternalDataSource.objects.create(team_id=self.team.pk,@@ -3942,7 +3948,7 @@ class TestExternalDataSource(APIBaseTest):assert table is not Noneself.assertEqual(table.name, "Accounts")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_direct_postgres_updates_connection_metadata(self, mock_get_source):source = ExternalDataSource.objects.create(team_id=self.team.pk,@@ -3986,7 +3992,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(connection_metadata["database"], "ducklake")self.assertEqual(connection_metadata["available_functions"], ["duckdb_functions", "date_bin"])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_direct_postgres_preserves_numeric_as_decimal(self, mock_get_source):_configure_source_mock_versioning(mock_get_source)source_mock = mock_get_source.return_value@@ -4084,7 +4090,7 @@ class TestExternalDataSource(APIBaseTest):assert response.json() == {"message": "This source name is reserved by PostHog."}assert not ExternalDataSource.objects.filter(team=self.team, prefix="managed_warehouse").exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_direct_postgres_does_not_require_prefix_namespace(self, mock_get_source):_configure_source_mock_versioning(mock_get_source)ExternalDataSource.objects.create(@@ -4141,7 +4147,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_201_CREATED)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_direct_postgres_creates_only_selected_tables(self, mock_get_source):_configure_source_mock_versioning(mock_get_source)source_mock = mock_get_source.return_value@@ -4219,7 +4225,7 @@ class TestExternalDataSource(APIBaseTest):1,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_direct_postgres_rejects_row_filters(self, mock_get_source):_configure_source_mock_versioning(mock_get_source)source_mock = mock_get_source.return_value@@ -4275,7 +4281,7 @@ class TestExternalDataSource(APIBaseTest):self.assertIn("not supported for direct-query sources", str(response.json()))self.assertFalse(ExternalDataSource.objects.filter(team_id=self.team.pk).exists())- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_direct_postgres_blank_schema_prefixes_table_names_and_preserves_physical_schema(self, mock_get_source):@@ -4358,18 +4364,18 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(analytics_schema.sync_type_config["schema_metadata"]["source_schema"], "analytics")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.get_primary_key_columns")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cdc_pg_connection")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_postgres_cdc_with_blank_schema_uses_physical_schema_metadata(self,mock_get_source,@@ -4458,18 +4464,18 @@ class TestExternalDataSource(APIBaseTest):assert mock_add_table.call_args.args[1:] == ("analytics", "events")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.get_primary_key_columns")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cdc_pg_connection")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_postgres_cdc_leaves_unenabled_schemas_without_sync_type(self,mock_get_source,@@ -4579,18 +4585,18 @@ class TestExternalDataSource(APIBaseTest):assert mock_add_table.call_args.args[1:] == ("analytics", "events")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.add_table")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.get_primary_key_columns")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cdc_pg_connection")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_postgres_cdc_rejects_table_without_primary_key(self,mock_get_source,@@ -4667,17 +4673,17 @@ class TestExternalDataSource(APIBaseTest):mock_setup_cdc_resources.assert_not_called()mock_add_table.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.get_primary_key_columns")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cdc_pg_connection")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.get_primary_key_columns")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.cdc_pg_connection")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_postgres_cdc_returns_400_when_pk_detection_connection_fails(self,mock_get_source,@@ -4754,13 +4760,13 @@ class TestExternalDataSource(APIBaseTest):mock_capture_exception.assert_not_called()@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_rejects_cdc_schemas_when_source_cdc_disabled(self,mock_get_source,@@ -4839,7 +4845,7 @@ class TestExternalDataSource(APIBaseTest):("both_absent_omits_key", None, None, None),])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_postgres_incremental_primary_key_fallback(self,_name: str,@@ -4929,7 +4935,7 @@ class TestExternalDataSource(APIBaseTest):("subset_passes_through", ["email", "name"], ["email", "name"]),])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_create_postgres_persists_enabled_columns_payload(self,_name: str,@@ -4986,7 +4992,7 @@ class TestExternalDataSource(APIBaseTest):schema = ExternalDataSchema.objects.get(team_id=self.team.pk, name="events")assert schema.enabled_columns == expected_persisted- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_refresh_schemas_renames_legacy_direct_query_rows(self, mock_get_source):# Direct-query mode opts in to eager renaming: the live `DataWarehouseTable` is rebuilt# from `schema_metadata` on every `refresh_schemas`, so renaming the row never orphans@@ -5086,7 +5092,7 @@ class TestExternalDataSource(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_database_schema_postgres_direct_allows_blank_schema(self, mock_get_source):source = PostgresSource()mock_get_source.return_value = source@@ -5126,7 +5132,7 @@ class TestExternalDataSource(APIBaseTest):validate.assert_called_once()self.assertEqual(validate.call_args.args[2], "direct")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_database_schema_postgres_requires_ssl_while_setting_the_source_up(self, mock_get_source):source = PostgresSource()mock_get_source.return_value = source@@ -5158,7 +5164,7 @@ class TestExternalDataSource(APIBaseTest):("non_postgres", "MySQL", True, None),])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_database_schema_xmin_available_gating(self, _name, source_type, supports_xmin, expected_xmin_available, mock_get_source):@@ -5329,8 +5335,8 @@ class TestExternalDataSource(APIBaseTest):("unexpected_source_error", True),])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_database_schema_captures_only_unexpected_source_errors(self, _name, expect_capture, mock_get_source, mock_capture_exception):@@ -5369,8 +5375,8 @@ class TestExternalDataSource(APIBaseTest):assert response.json()["message"] == str(error)mock_capture_exception.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_database_schema_rejects_source_without_schema_discovery(self, mock_get_source, mock_capture_exception):# AmazonS3 deliberately omits get_schemas, so the base raises NotImplementedError. The endpoint# must return a clean 400 without capturing it as a server error, mirroring `setup`.@@ -5482,7 +5488,7 @@ class TestExternalDataSource(APIBaseTest):for table in STRIPE_ENDPOINTS:assert table in table_names- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_database_schema_does_not_request_row_counts(self, mock_get_source):parsed_config = Mock()mock_source = mock_get_source.return_value@@ -5943,6 +5949,52 @@ class TestExternalDataSource(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert len(response.json()) == expected_count+ @parameterized.expand(+ [+ ("malformed_after", "?after=yesterday"),+ ("malformed_before", "?before=not-a-date"),+ ("malformed_both", "?after=yesterday&before=not-a-date"),+ ]+ )+ def test_source_jobs_rejects_malformed_timestamp(self, _name, query_string):+ source = self._create_external_data_source()+ schema = self._create_external_data_schema(source.pk)+ ExternalDataJob.objects.create(+ team=self.team,+ pipeline=source,+ schema=schema,+ status=ExternalDataJob.Status.COMPLETED,+ pipeline_version=ExternalDataJob.PipelineVersion.V1,+ )++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/jobs{query_string}",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand(+ [+ ("valid_after", "?after=2024-07-01T12:00:00.000Z", status.HTTP_200_OK),+ ("valid_before", "?before=2024-07-01T12:00:00.000Z", status.HTTP_200_OK),+ ("empty_values", "?after=&before=", status.HTTP_200_OK),+ ]+ )+ def test_source_jobs_accepts_valid_timestamps(self, _name, query_string, expected_status):+ source = self._create_external_data_source()+ schema = self._create_external_data_schema(source.pk)+ ExternalDataJob.objects.create(+ team=self.team,+ pipeline=source,+ schema=schema,+ status=ExternalDataJob.Status.COMPLETED,+ pipeline_version=ExternalDataJob.PipelineVersion.V1,+ )++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/jobs{query_string}",+ )+ assert response.status_code == expected_status+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",return_value=(True, None),@@ -6867,7 +6919,7 @@ class TestExternalDataSource(APIBaseTest):mock_probe_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.trigger_external_data_source_workflow")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")@patch(@@ -6909,7 +6961,7 @@ class TestExternalDataSource(APIBaseTest):assert row.sensitive_config["refresh_token"] == "rotated-RT"@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.trigger_external_data_source_workflow")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.make_tracked_session")@patch(@@ -7434,7 +7486,7 @@ class TestExternalDataSource(APIBaseTest):source.refresh_from_db()assert source.prefix == "Updated name"- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_update_direct_postgres_schema_filter_refreshes_existing_schemas(self, mock_get_source):_configure_source_mock_versioning(mock_get_source)source = ExternalDataSource.objects.create(@@ -7515,7 +7567,7 @@ class TestExternalDataSource(APIBaseTest):assert matching_schema.sync_type_config["schema_metadata"]["source_schema"] == "analytics"assert filtered_out_schema.deleted is True- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.SourceRegistry.get_source")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.SourceRegistry.get_source")def test_update_direct_postgres_schema_filter_preserves_selected_table_for_same_physical_schema(self, mock_get_source):@@ -10172,7 +10224,7 @@ class TestDestroySourceCleansUpWebhook(APIBaseTest):assert hog_function.enabled is Falsemock_delete_webhook.assert_called_once()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.delete_webhook",side_effect=Exception("Stripe API error"),@@ -10440,7 +10492,7 @@ class TestCheckCDCPrerequisitesForSource(APIBaseTest):("ssh_tunnel_error", BaseSSHTunnelForwarderError("Could not establish session to SSH gateway")),])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")def test_connection_failure_returns_400_without_capture(self, _name, exc, mock_capture) -> None:source = _make_postgres_source(self.team.pk, self.user)with patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=exc):@@ -10454,7 +10506,7 @@ class TestCheckCDCPrerequisitesForSource(APIBaseTest):# User/upstream connection failures must not pollute error tracking.mock_capture.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=ValueError("unexpected bug"))def test_unexpected_error_is_still_captured(self, _mock_validate, mock_capture) -> None:source = _make_postgres_source(self.team.pk, self.user)@@ -10506,7 +10558,7 @@ class TestCheckCDCPrerequisitesWizard(APIBaseTest):("temporary_host_resolution_error", TemporaryHostResolutionError("db.example.com")),])- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch.object(PostgresSource, "is_database_host_valid", return_value=(True, None))@patch.object(PostgresSource, "ssh_tunnel_is_valid", return_value=(True, None))def test_connection_failure_returns_400_without_capture(@@ -10533,7 +10585,7 @@ class TestCheckCDCPrerequisitesWizard(APIBaseTest):assert response.status_code == 400assert "only supported for" in response.json()["message"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch.object(PostgresSource, "is_database_host_valid", return_value=(True, None))@patch.object(PostgresSource, "ssh_tunnel_is_valid", return_value=(True, None))@patch.object(PostgresSource, "check_cdc_prerequisites", side_effect=ValueError("unexpected bug"))@@ -10546,7 +10598,7 @@ class TestCheckCDCPrerequisitesWizard(APIBaseTest):class TestEnableCDC(APIBaseTest):@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)def test_enable_cdc_rejects_source_type_without_cdc_support(self, _flag) -> None:@@ -10569,7 +10621,7 @@ class TestEnableCDC(APIBaseTest):assert "CDC is not supported" in response.json()["message"]@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=False,)def test_enable_cdc_rejects_when_team_flag_off(self, _flag) -> None:@@ -10582,7 +10634,7 @@ class TestEnableCDC(APIBaseTest):assert response.status_code == 403@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)def test_enable_cdc_rejects_when_already_enabled(self, _flag) -> None:@@ -10602,7 +10654,7 @@ class TestEnableCDC(APIBaseTest):])@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)def test_enable_cdc_rejects_invalid_management_mode(self, _name: str, mode_value, _flag) -> None:@@ -10616,7 +10668,7 @@ class TestEnableCDC(APIBaseTest):assert "cdc_management_mode" in response.json()["message"]@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -10654,10 +10706,10 @@ class TestEnableCDC(APIBaseTest):])@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")def test_enable_cdc_connection_failure_returns_400_without_capture(self, _name, exc, mock_capture, _flag) -> None:source = _make_postgres_source(self.team.pk, self.user)with patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=exc):@@ -10672,10 +10724,10 @@ class TestEnableCDC(APIBaseTest):mock_capture.assert_not_called()@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch.object(PostgresCDCAdapter, "validate_prerequisites", side_effect=ValueError("unexpected bug"))def test_enable_cdc_unexpected_error_is_still_captured(self, _check, mock_capture, _flag) -> None:source = _make_postgres_source(self.team.pk, self.user)@@ -10688,7 +10740,7 @@ class TestEnableCDC(APIBaseTest):mock_capture.assert_called_once()@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -10696,11 +10748,13 @@ class TestEnableCDC(APIBaseTest):return_value=[],)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.sync_cdc_extraction_schedule")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ensure_cdc_slot_cleanup_schedule"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.sync_cdc_extraction_schedule"+ )+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_cdc_slot_cleanup_schedule")def test_enable_cdc_posthog_managed_success(self,@@ -10762,7 +10816,7 @@ class TestEnableCDC(APIBaseTest):mock_ensure_cleanup.assert_called_once()@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -10770,11 +10824,13 @@ class TestEnableCDC(APIBaseTest):return_value=[],)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources"+ )+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.sync_cdc_extraction_schedule")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.sync_cdc_extraction_schedule")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ensure_cdc_slot_cleanup_schedule"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_cdc_slot_cleanup_schedule")def test_enable_cdc_succeeds_for_supabase(self,@@ -10797,7 +10853,7 @@ class TestEnableCDC(APIBaseTest):assert response.status_code == 200, response.content@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -10805,11 +10861,13 @@ class TestEnableCDC(APIBaseTest):return_value=[],)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources"+ )+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.sync_cdc_extraction_schedule")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.sync_cdc_extraction_schedule")@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ensure_cdc_slot_cleanup_schedule"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_cdc_slot_cleanup_schedule")def test_enable_cdc_self_managed_passes_publication_name(self,@@ -10857,7 +10915,7 @@ class TestEnableCDC(APIBaseTest):assert ji["cdc_publication_name"] == "customer_pub"@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -10865,7 +10923,7 @@ class TestEnableCDC(APIBaseTest):return_value=[],)@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.ExternalDataSourceViewSet._setup_cdc_resources"+ "products.warehouse_sources.backend.presentation.views.external_data_source.viewset.ExternalDataSourceViewSet._setup_cdc_resources")def test_enable_cdc_returns_400_when_slot_setup_fails(self, mock_setup_cdc_resources, _check, _flag) -> None:source = _make_postgres_source(self.team.pk, self.user)@@ -10885,7 +10943,7 @@ class TestEnableCDC(APIBaseTest):assert (source.job_inputs or {}).get("cdc_enabled") is not True@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -10956,7 +11014,7 @@ class TestEnableCDC(APIBaseTest):assert source.deleted is False@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_enabled_for_team",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_enabled_for_team",return_value=True,)@patch(@@ -11091,11 +11149,12 @@ class TestDisableCDC(APIBaseTest):assert non_cdc_schema.sync_type == ExternalDataSchema.SyncType.INCREMENTALassert non_cdc_schema.should_sync is True+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.purge_buffer_prefix")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",return_value=None,)- def test_disable_cdc_clears_an_earlier_auto_disable(self, _cleanup) -> None:+ def test_disable_cdc_clears_an_earlier_auto_disable(self, _cleanup, _purge_buffer_prefix) -> None:# PostHog can halt a CDC schema before the user gives up on CDC. The halt must not# survive their disable, or the failure digest keeps emailing them about a sync# they switched off themselves.@@ -11122,7 +11181,7 @@ class TestDisableCDC(APIBaseTest):halted_schema.refresh_from_db()assert halted_schema.auto_disabled_at is None- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.purge_buffer_prefix")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.purge_buffer_prefix")def test_disable_cdc_requires_editor_on_every_table(self, mock_purge) -> None:# A table can be locked below source-level editor; the per-table gate must run# before any destructive step (job cancel, slot drop, buffer purge, schema reset).@@ -11149,7 +11208,7 @@ class TestDisableCDC(APIBaseTest):cdc_schema.refresh_from_db()assert cdc_schema.sync_type == ExternalDataSchema.SyncType.CDC # nothing was reset- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.purge_buffer_prefix")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.purge_buffer_prefix")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",return_value=None,@@ -11220,7 +11279,9 @@ class TestDisableCDC(APIBaseTest):"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",return_value=None,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cancel_external_data_workflow")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.cancel_external_data_workflow"+ )def test_disable_cdc_cancels_running_workflow(self, mock_cancel, _cleanup) -> None:source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)cdc_schema = ExternalDataSchema.objects.create(@@ -11249,7 +11310,9 @@ class TestDisableCDC(APIBaseTest):"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",return_value=None,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cancel_external_data_workflow")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.cancel_external_data_workflow"+ )def test_disable_cdc_does_not_cancel_non_cdc_running_jobs(self, mock_cancel, _cleanup) -> None:# A running incremental sync on the same source must NOT be cancelled by disable_cdc.source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)@@ -11279,7 +11342,9 @@ class TestDisableCDC(APIBaseTest):"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.cleanup_resources",return_value=None,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.cancel_external_data_workflow")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.cancel_external_data_workflow"+ )def test_disable_cdc_does_not_cancel_non_running_workflow(self, mock_cancel, _cleanup) -> None:source = _make_postgres_source(self.team.pk, self.user, cdc_enabled=True)ExternalDataJob.objects.create(@@ -11822,10 +11887,11 @@ class TestCDCStatus(APIBaseTest):source = _make_postgres_source(self.team.pk, self.user)response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/cdc_status/")assert response.status_code == 200, response.content- assert response.json() == {"enabled": False}+ assert response.json()["enabled"] is False+ assert "management_mode" not in response.json()@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_extraction_schedule_paused",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_extraction_schedule_paused",return_value=False,)@patch(@@ -11849,7 +11915,7 @@ class TestCDCStatus(APIBaseTest):assert mock_get_status.call_args.args[0].pk == source.pk@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_extraction_schedule_paused",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_extraction_schedule_paused",return_value=True,)@patch(@@ -11863,7 +11929,7 @@ class TestCDCStatus(APIBaseTest):assert response.json()["schedule_paused"] is True@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_extraction_schedule_paused",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_extraction_schedule_paused",side_effect=Exception("temporal unavailable"),)@patch(@@ -11878,7 +11944,7 @@ class TestCDCStatus(APIBaseTest):assert response.json()["schedule_paused"] is False@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.is_cdc_extraction_schedule_paused",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.is_cdc_extraction_schedule_paused",return_value=False,)@patch(@@ -11937,8 +12003,12 @@ class TestResumeCDC(APIBaseTest):assert response.status_code == 400assert "nothing to resume" in response.json()["message"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.sync_cdc_extraction_schedule")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.unpause_cdc_extraction_schedule")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.sync_cdc_extraction_schedule"+ )+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.unpause_cdc_extraction_schedule"+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status",return_value={"slot_exists": True, "publication_exists": True, "lag_bytes": 128},@@ -11963,7 +12033,9 @@ class TestResumeCDC(APIBaseTest):assert "cdc_extraction_paused" not in schema.sync_type_configassert schema.sync_halted is False- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.unpause_cdc_extraction_schedule")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.unpause_cdc_extraction_schedule"+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status")@@ -11979,7 +12051,9 @@ class TestResumeCDC(APIBaseTest):mock_unpause.assert_not_called()mock_get_status.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.unpause_cdc_extraction_schedule")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.unpause_cdc_extraction_schedule"+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status",side_effect=psycopg.OperationalError("password authentication failed"),@@ -11994,7 +12068,9 @@ class TestResumeCDC(APIBaseTest):assert "check the credentials" in response.json()["message"]mock_unpause.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.unpause_cdc_extraction_schedule")+ @patch(+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.unpause_cdc_extraction_schedule"+ )@patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.adapter.PostgresCDCAdapter.get_status",return_value={"slot_exists": False, "publication_exists": True, "lag_bytes": None},@@ -12048,7 +12124,7 @@ class TestExternalDataSourceConnectLink(APIBaseTest):class TestExternalDataSourceSetup(APIBaseTest):# Stripe enables revenue analytics, whose post-create view sync builds the HogQL Database — patched# out here so the test exercises setup's own logic rather than that unrelated side effect.- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",@@ -12079,7 +12155,7 @@ class TestExternalDataSourceSetup(APIBaseTest):assert synced.exists()assert all(s.sync_type in ("incremental", "append", "full_refresh") for s in synced)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",@@ -12099,7 +12175,7 @@ class TestExternalDataSourceSetup(APIBaseTest):source = ExternalDataSource.objects.get(pk=response.json()["id"])assert source.direct_query_enabled is False- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")def test_setup_rejects_source_without_schema_discovery(self, mock_capture_exception):# AmazonS3 doesn't implement get_schemas, so the base raises NotImplementedError.response = self.client.post(@@ -12111,7 +12187,7 @@ class TestExternalDataSourceSetup(APIBaseTest):mock_capture_exception.assert_not_called()assert not ExternalDataSource.objects.filter(team=self.team).exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.capture_exception")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",return_value=(True, None),@@ -12186,7 +12262,7 @@ class TestExternalDataSourceSetup(APIBaseTest):},)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook",@@ -12226,7 +12302,7 @@ class TestExternalDataSourceSetup(APIBaseTest):assert hog_function.inputs is not Noneassert hog_function.inputs["source_id"]["value"] == data["id"]- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook",@@ -12260,7 +12336,7 @@ class TestExternalDataSourceSetup(APIBaseTest):# The orphaned handler is removed so nothing dangles.assert not HogFunction.objects.filter(team=self.team, type="warehouse_source_webhook", deleted=False).exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.create_webhook")@patch(@@ -12283,7 +12359,7 @@ class TestExternalDataSourceSetup(APIBaseTest):customer = schemas.get(name=STRIPE_CUSTOMER_RESOURCE_NAME)assert customer.sync_type in ("incremental", "append", "full_refresh")- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",@@ -12307,7 +12383,7 @@ class TestExternalDataSourceSetup(APIBaseTest):# Every other readable table still gets the normal polling default.assert schemas.filter(should_sync=True).exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",@@ -12351,7 +12427,7 @@ class TestExternalDataSourceSetup(APIBaseTest):**kwargs,)- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",@@ -12450,7 +12526,7 @@ class TestExternalDataSourceSetup(APIBaseTest):# The teammate's stash must survive untouched.assert PendingSourceCredential.objects.for_team(self.team.pk).filter(pk=credential.pk).exists()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.ensure_person_join")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.base.ensure_person_join")@patch("products.data_modeling.backend.models.datawarehouse_managed_viewset.DataWarehouseManagedViewSet.sync_views")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",@@ -13728,7 +13804,7 @@ class TestExternalDataSourcePreviewAndCustomPayload(APIBaseTest):assert [table["table"] for table in response.json()] == ["users"]@patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.trigger_external_data_source_workflow"+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.trigger_external_data_source_workflow")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.custom.source.CustomSource.validate_credentials",@@ -13757,7 +13833,7 @@ class TestGetDirectConnectionMetadata(SimpleTestCase):impl.get_non_retryable_errors.return_value = non_retryable or {}return impl- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.helpers.capture_exception")def test_expected_connection_error_is_not_captured(self, mock_capture):# An unreachable customer host fails the best-effort metadata probe — already surfaced by# credential validation, so it must degrade to the fallback without flooding error tracking.@@ -13771,7 +13847,7 @@ class TestGetDirectConnectionMetadata(SimpleTestCase):self.assertEqual(result, fallback)mock_capture.assert_not_called()- @patch("products.warehouse_sources.backend.presentation.views.external_data_source.capture_exception")+ @patch("products.warehouse_sources.backend.presentation.views.external_data_source.helpers.capture_exception")def test_unexpected_error_is_still_captured(self, mock_capture):error = ValueError("unexpected bug in metadata probe")impl = self._source_impl(error)@@ -14165,3 +14241,23 @@ class TestExternalDataSourceAPIKeyScopes(APIBaseTest):assert response.status_code != status.HTTP_403_FORBIDDEN, response.contentelse:assert response.status_code == status.HTTP_403_FORBIDDEN, response.content++ @parameterized.expand(+ [+ ("external_data_source:read", True),+ ("external_data_source:write", True),+ ("another_resource:read", False),+ ]+ )+ def test_direct_connection_options_is_a_read_action(self, scope: str, should_have_access: bool) -> None:+ self.client.force_authenticate(None)++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/direct_connection_options/",+ headers={"authorization": f"Bearer {self._make_api_key([scope])}"},+ )++ if should_have_access:+ assert response.status_code != status.HTTP_403_FORBIDDEN, response.content+ else:+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.contentdiff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py b/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.pyindex a20ef47a82ac..fd7f42e5726d 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source_end_to_end.py@@ -45,7 +45,7 @@ def api_client(user):return_value=(True, None),),mock.patch(- "products.warehouse_sources.backend.presentation.views.external_data_source.bulk_create_external_data_job_schedules",+ "products.warehouse_sources.backend.presentation.views.external_data_source.base.bulk_create_external_data_job_schedules",return_value=[],) as mock_sync_workflow,mock.patch.object(DataWarehouseSavedQuery, "schedule_materialization"),diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex ddb13d9a148e..6dedbf7559ff 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -4926,6 +4926,77 @@ export interface ExternalDataSourceBulkUpdateSchemasApi {schemas: ExternalDataSourceBulkUpdateSchemaApi[]}+/**+ * * `posthog` - posthog+ * * `self_managed` - self_managed+ */+export type ManagementModeEnumApi = (typeof ManagementModeEnumApi)[keyof typeof ManagementModeEnumApi]++export const ManagementModeEnumApi = {+ Posthog: 'posthog',+ SelfManaged: 'self_managed',+} as const++export interface CdcStatusApi {+ /** Whether CDC is enabled on this source. */+ enabled: boolean+ /** Who owns the slot and publication: PostHog or the customer.+ *+ * * `posthog` - posthog+ * * `self_managed` - self_managed */+ management_mode?: ManagementModeEnumApi+ /** Replication slot PostHog consumes from. Empty when unset. */+ slot_name?: string+ /** Publication PostHog reads changes from. Empty when unset. */+ publication_name?: string+ /** Lag in MB above which the UI warns. */+ lag_warning_threshold_mb?: number+ /** Lag in MB above which the UI alerts. */+ lag_critical_threshold_mb?: number+ /** True when a non-retryable failure paused the extraction schedule; the UI then offers Resume instead of Repair. Degrades to false when the schedule lookup fails. */+ schedule_paused?: boolean+ /** Whether the replication slot exists on the source, when the source was reachable. */+ slot_exists?: boolean+ /** Whether the publication exists on the source, when the source was reachable. */+ publication_exists?: boolean+ /**+ * Current slot lag in bytes, when the source was reachable.+ * @nullable+ */+ lag_bytes?: number | null+ /** Tables in the publication, when the source was reachable and a publication exists. */+ published_tables?: string[]+}++export interface CreateWebhookResponseApi {+ /** Whether the webhook was created and registered with the source. */+ success: boolean+ /**+ * The PostHog endpoint the external service delivers events to.+ * @nullable+ */+ webhook_url: string | null+ /**+ * Why creation failed, when success is false.+ * @nullable+ */+ error: string | null+ /** Inputs the external service needs before delivery works. Submit via update_webhook_inputs. */+ pending_inputs: string[]+}++export interface DeleteWebhookResponseApi {+ /** Whether the webhook delivery function was deleted. */+ success: boolean+ /** Whether the webhook was also removed from the external service. False when the source config was already gone and only the local function was cleaned up, or when the external call failed. */+ external_deleted: boolean+ /**+ * Why the external deletion failed, when external_deleted is false.+ * @nullable+ */+ error: string | null+}+/*** Response shape for a source's destination set.*/@@ -4934,6 +5005,193 @@ export interface SourceDestinationsApi {destination_ids: string[]}+export interface CdcEnableResponseApi {+ /** Whether CDC was enabled on the source. */+ success: boolean+ /** Whether the extraction and cleanup schedules could be created. False means CDC is enabled but scheduling failed; the schedule self-heals on the first CDC schema toggle. */+ schedules_ready: boolean+}++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++export interface SimpleExternalDataSchemaApi {+ readonly id: string+ /** @maxLength 400 */+ name: string+ /**+ * @maxLength 400+ * @nullable+ */+ label?: string | null+ should_sync?: boolean+ /** @nullable */+ last_synced_at?: string | null+ sync_type?: ExternalDataSchemaSyncTypeEnumApi | BlankEnumApi | null+}++export interface ExternalDataJobSerializersApi {+ readonly id: string+ readonly created_at: string+ /** @nullable */+ readonly created_by: number | null+ /** @nullable */+ readonly finished_at: string | null+ readonly status: string+ readonly schema: SimpleExternalDataSchemaApi+ /** @nullable */+ readonly rows_synced: number | null+ /**+ * The latest error that occurred during this run.+ * @nullable+ */+ readonly latest_error: string | null+ /** @nullable */+ readonly workflow_run_id: string | null+ /**+ * For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob rows produced per sync: `incremental_merge` (consolidated table) vs `scd2_append` (cdc-only history table). `null` for non-CDC syncs. Read from `schema_snapshot`.+ * @nullable+ */+ readonly cdc_write_mode: string | null+ /**+ * Whether the rows synced by this job count toward billing. `false` for system-initiated runs the customer isn't charged for (e.g. rebuilding a table after an internal issue). `null` on legacy rows and means billable.+ * @nullable+ */+ readonly billable: boolean | null+ /** Destinations this run delivered to, snapshotted when it started. Empty on runs that predate destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts the rows read from the source once, not once per destination. */+ readonly destination_ids: readonly string[]+}++export interface UpdateWebhookInputsResponseApi {+ /** Whether the inputs were saved and pushed to the external service. */+ success: boolean+}++/**+ * Resource name to external schema id, as configured on the webhook function.+ */+export type WebhookInfoResponseApiSchemaMapping = { [key: string]: string }++/**+ * * `hog` - hog+ * * `liquid` - liquid+ */+export type HogFunctionTemplatingEnumApi =+ (typeof HogFunctionTemplatingEnumApi)[keyof typeof HogFunctionTemplatingEnumApi]++export const HogFunctionTemplatingEnumApi = {+ Hog: 'hog',+ Liquid: 'liquid',+} as const++export interface InputsItemApi {+ value?: unknown+ templating?: HogFunctionTemplatingEnumApi+ readonly bytecode: readonly unknown[]+ readonly order: number+ readonly transpiled: unknown+}++/**+ * Current webhook function inputs keyed by the source's declared webhook field names.+ */+export type WebhookInfoResponseApiInputs = { [key: string]: InputsItemApi }++/**+ * Delivery health reported by the pipeline: `state` and `tokens` counters.+ */+export type WebhookHogFunctionApiStatus = { [key: string]: unknown }++export interface WebhookHogFunctionApi {+ /** ID of the webhook delivery hog function. */+ id: string+ /** Name of the webhook delivery hog function. */+ name: string+ /** Whether the webhook delivery function is enabled. */+ enabled: boolean+ /** When the webhook delivery function was created (ISO 8601). */+ created_at: string+ /** Delivery health reported by the pipeline: `state` and `tokens` counters. */+ status: WebhookHogFunctionApiStatus+}++export interface WebhookExternalStatusApi {+ /** Whether the webhook exists on the external service. */+ exists: boolean+ /**+ * The webhook URL on the external service.+ * @nullable+ */+ url: string | null+ /**+ * Events the external webhook is subscribed to.+ * @nullable+ */+ enabled_events: string[] | null+ /**+ * Delivery health as the external service reports it (e.g. 'enabled').+ * @nullable+ */+ status: string | null+ /**+ * Description the external service holds for it.+ * @nullable+ */+ description: string | null+ /**+ * When the external webhook was created.+ * @nullable+ */+ created_at: string | null+ /**+ * Vendor API version the endpoint delivers at, when pinned.+ * @nullable+ */+ api_version: string | null+ /**+ * Read error the external service returned, if any.+ * @nullable+ */+ error: string | null+}++export interface WebhookInfoResponseApi {+ /** Whether the source type supports webhooks at all. When false, the other fields are absent. */+ supports_webhooks: boolean+ /** Whether a PostHog webhook delivery function exists for this source yet. */+ exists: boolean+ /**+ * Set when the connection's credentials can never create the webhook, so only manual setup is left. Null means 'not known to be blocked'.+ * @nullable+ */+ auto_creation_blocked_reason: string | null+ /** The webhook delivery function, present once the webhook exists. */+ hog_function: WebhookHogFunctionApi | null+ /**+ * The PostHog endpoint the external service delivers events to.+ * @nullable+ */+ webhook_url: string | null+ /** Resource name to external schema id, as configured on the webhook function. */+ schema_mapping: WebhookInfoResponseApiSchemaMapping+ /** Current webhook function inputs keyed by the source's declared webhook field names. */+ inputs?: WebhookInfoResponseApiInputs+ /** Live webhook state as the external service reports it, when it could be read. */+ external_status: WebhookExternalStatusApi | null+ /** Desired provider events not yet on the webhook (manual setup, or created before a new table). */+ missing_events?: string[]+}++export interface CdcPrerequisitesResponseApi {+ /** Whether the source satisfies every CDC prerequisite. */+ valid: boolean+ /** Unmet prerequisites, empty when valid is true. */+ errors: string[]+}+/*** * `oauth` - oauth* * `credentials` - credentials@@ -13634,6 +13892,25 @@ export type ExternalDataSourcesListParams = {search?: string}+export type ExternalDataSourcesJobsListParams = {+ /**+ * ISO timestamp — only return jobs created after this date.+ */+ after?: string+ /**+ * ISO timestamp — only return jobs created before this date.+ */+ before?: string+ /**+ * Filter jobs by table schema names.+ */+ schemas?: string[]+ /**+ * A search term.+ */+ search?: string+}+export type ExternalDataSourcesRepairCdcCreate200 = {success?: booleanschemas_reset?: number@@ -13643,11 +13920,6 @@ export type ExternalDataSourcesResumeCdcCreate200 = {success?: boolean}-export type ExternalDataSourcesCheckCdcPrerequisitesCreate200 = {- valid?: boolean- errors?: string[]-}-export type ExternalDataSourcesConnectLinkRetrieveParams = {/*** The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.tsindex 405f4512ac09..d82584513470 100644--- a/products/warehouse_sources/frontend/generated/api.ts+++ b/products/warehouse_sources/frontend/generated/api.ts@@ -9,12 +9,18 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* OpenAPI spec version: 1.0.0*/import type {+ CdcEnableResponseApi,+ CdcPrerequisitesResponseApi,+ CdcStatusApi,+ CreateWebhookResponseApi,DatabaseSchemaRequestApi,+ DeleteWebhookResponseApi,DirectConnectionSourceOptionApi,DraftCustomManifestRequestApi,DraftCustomManifestResponseApi,ExternalDataDestinationApi,ExternalDataDestinationsListParams,+ ExternalDataJobSerializersApi,ExternalDataSchemaApi,ExternalDataSchemasCancelCreate200,ExternalDataSchemasListParams,@@ -24,8 +30,8 @@ import type {ExternalDataSourceCreateApi,ExternalDataSourceCreateResponseApi,ExternalDataSourceSerializersApi,- ExternalDataSourcesCheckCdcPrerequisitesCreate200,ExternalDataSourcesConnectLinkRetrieveParams,+ ExternalDataSourcesJobsListParams,ExternalDataSourcesListParams,ExternalDataSourcesOauthAccountsRetrieveParams,ExternalDataSourcesRepairCdcCreate200,@@ -51,8 +57,10 @@ import type {SourcePreviewResponseApi,SourceSetupApi,SourceSetupResponseApi,+ UpdateWebhookInputsResponseApi,WarehouseColumnStatisticsApi,WarehouseColumnStatisticsListParams,+ WebhookInfoResponseApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -636,8 +644,8 @@ export const externalDataSourcesCdcStatusRetrieve = async (projectId: string,id: string,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesCdcStatusRetrieveUrl(projectId, id), {+): Promise<CdcStatusApi> => {+ return apiMutator<CdcStatusApi>(getExternalDataSourcesCdcStatusRetrieveUrl(projectId, id), {...options,method: 'GET',})@@ -685,8 +693,8 @@ export const externalDataSourcesCreateWebhookCreate = async (id: string,externalDataSourceSerializersApi: NonReadonly<ExternalDataSourceSerializersApi>,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesCreateWebhookCreateUrl(projectId, id), {+): Promise<CreateWebhookResponseApi> => {+ return apiMutator<CreateWebhookResponseApi>(getExternalDataSourcesCreateWebhookCreateUrl(projectId, id), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -706,8 +714,8 @@ export const externalDataSourcesDeleteWebhookCreate = async (id: string,externalDataSourceSerializersApi: NonReadonly<ExternalDataSourceSerializersApi>,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesDeleteWebhookCreateUrl(projectId, id), {+): Promise<DeleteWebhookResponseApi> => {+ return apiMutator<DeleteWebhookResponseApi>(getExternalDataSourcesDeleteWebhookCreateUrl(projectId, id), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -809,8 +817,8 @@ export const externalDataSourcesEnableCdcCreate = async (id: string,externalDataSourceSerializersApi: NonReadonly<ExternalDataSourceSerializersApi>,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesEnableCdcCreateUrl(projectId, id), {+): Promise<CdcEnableResponseApi> => {+ return apiMutator<CdcEnableResponseApi>(getExternalDataSourcesEnableCdcCreateUrl(projectId, id), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -818,19 +826,36 @@ export const externalDataSourcesEnableCdcCreate = async (})}-export const getExternalDataSourcesJobsRetrieveUrl = (projectId: string, id: string) => {- return `/api/projects/${projectId}/external_data_sources/${id}/jobs/`+export const getExternalDataSourcesJobsListUrl = (+ projectId: string,+ id: string,+ params?: ExternalDataSourcesJobsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/external_data_sources/${id}/jobs/?${stringifiedParams}`+ : `/api/projects/${projectId}/external_data_sources/${id}/jobs/`}/*** Create, Read, Update and Delete External data Sources.*/-export const externalDataSourcesJobsRetrieve = async (+export const externalDataSourcesJobsList = async (projectId: string,id: string,+ params?: ExternalDataSourcesJobsListParams,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesJobsRetrieveUrl(projectId, id), {+): Promise<ExternalDataJobSerializersApi[]> => {+ return apiMutator<ExternalDataJobSerializersApi[]>(getExternalDataSourcesJobsListUrl(projectId, id, params), {...options,method: 'GET',})@@ -990,13 +1015,16 @@ export const externalDataSourcesUpdateWebhookInputsCreate = async (id: string,externalDataSourceSerializersApi: NonReadonly<ExternalDataSourceSerializersApi>,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesUpdateWebhookInputsCreateUrl(projectId, id), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(externalDataSourceSerializersApi),- })+): Promise<UpdateWebhookInputsResponseApi> => {+ return apiMutator<UpdateWebhookInputsResponseApi>(+ getExternalDataSourcesUpdateWebhookInputsCreateUrl(projectId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(externalDataSourceSerializersApi),+ }+ )}export const getExternalDataSourcesWebhookInfoRetrieveUrl = (projectId: string, id: string) => {@@ -1010,8 +1038,8 @@ export const externalDataSourcesWebhookInfoRetrieve = async (projectId: string,id: string,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getExternalDataSourcesWebhookInfoRetrieveUrl(projectId, id), {+): Promise<WebhookInfoResponseApi> => {+ return apiMutator<WebhookInfoResponseApi>(getExternalDataSourcesWebhookInfoRetrieveUrl(projectId, id), {...options,method: 'GET',})@@ -1030,14 +1058,11 @@ export const getExternalDataSourcesCheckCdcPrerequisitesCreateUrl = (projectId:export const externalDataSourcesCheckCdcPrerequisitesCreate = async (projectId: string,options?: RequestInit-): Promise<ExternalDataSourcesCheckCdcPrerequisitesCreate200> => {- return apiMutator<ExternalDataSourcesCheckCdcPrerequisitesCreate200>(- getExternalDataSourcesCheckCdcPrerequisitesCreateUrl(projectId),- {- ...options,- method: 'POST',- }- )+): Promise<CdcPrerequisitesResponseApi> => {+ return apiMutator<CdcPrerequisitesResponseApi>(getExternalDataSourcesCheckCdcPrerequisitesCreateUrl(projectId), {+ ...options,+ method: 'POST',+ })}export const getExternalDataSourcesConnectLinkRetrieveUrl = (diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 8cb409790443..c1715085b865 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -456,8 +456,8 @@ tools:external-data-sources-enable-cdc-create:operation: external_data_sources_enable_cdc_createenabled: false- external-data-sources-jobs:- operation: external_data_sources_jobs_retrieve+ external-data-sources-jobs-list:+ operation: external_data_sources_jobs_listenabled: falseexternal-data-sources-list:operation: external_data_sources_listdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 8e40086cfe04..9fd817324c8d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17775,6 +17775,63 @@ export namespace Schemas {max_selections?: number | null;}+ export interface CdcEnableResponse {+ /** Whether CDC was enabled on the source. */+ success: boolean;+ /** Whether the extraction and cleanup schedules could be created. False means CDC is enabled but scheduling failed; the schedule self-heals on the first CDC schema toggle. */+ schedules_ready: boolean;+ }++ export interface CdcPrerequisitesResponse {+ /** Whether the source satisfies every CDC prerequisite. */+ valid: boolean;+ /** Unmet prerequisites, empty when valid is true. */+ errors: string[];+ }++ /**+ * * `posthog` - posthog+ * * `self_managed` - self_managed+ */+ export type ManagementModeEnum = typeof ManagementModeEnum[keyof typeof ManagementModeEnum];+++ export const ManagementModeEnum = {+ Posthog: 'posthog',+ SelfManaged: 'self_managed',+ } as const;++ export interface CdcStatus {+ /** Whether CDC is enabled on this source. */+ enabled: boolean;+ /** Who owns the slot and publication: PostHog or the customer.+ *+ * * `posthog` - posthog+ * * `self_managed` - self_managed */+ management_mode?: ManagementModeEnum;+ /** Replication slot PostHog consumes from. Empty when unset. */+ slot_name?: string;+ /** Publication PostHog reads changes from. Empty when unset. */+ publication_name?: string;+ /** Lag in MB above which the UI warns. */+ lag_warning_threshold_mb?: number;+ /** Lag in MB above which the UI alerts. */+ lag_critical_threshold_mb?: number;+ /** True when a non-retryable failure paused the extraction schedule; the UI then offers Resume instead of Repair. Degrades to false when the schedule lookup fails. */+ schedule_paused?: boolean;+ /** Whether the replication slot exists on the source, when the source was reachable. */+ slot_exists?: boolean;+ /** Whether the publication exists on the source, when the source was reachable. */+ publication_exists?: boolean;+ /**+ * Current slot lag in bytes, when the source was reachable.+ * @nullable+ */+ lag_bytes?: number | null;+ /** Tables in the publication, when the source was reachable and a publication exists. */+ published_tables?: string[];+ }+/*** * `consolidated` - consolidated* * `cdc_only` - cdc_only@@ -21217,6 +21274,23 @@ export namespace Schemas {assets?: CreateVersionFromSourceInputAssets;}+ export interface CreateWebhookResponse {+ /** Whether the webhook was created and registered with the source. */+ success: boolean;+ /**+ * The PostHog endpoint the external service delivers events to.+ * @nullable+ */+ webhook_url: string | null;+ /**+ * Why creation failed, when success is false.+ * @nullable+ */+ error: string | null;+ /** Inputs the external service needs before delivery works. Submit via update_webhook_inputs. */+ pending_inputs: string[];+ }+/*** * `user` - user* * `ai_generated` - ai_generated@@ -28936,6 +29010,18 @@ export namespace Schemas {org?: string;}+ export interface DeleteWebhookResponse {+ /** Whether the webhook delivery function was deleted. */+ success: boolean;+ /** Whether the webhook was also removed from the external service. False when the source config was already gone and only the local function was cleaned up, or when the external call failed. */+ external_deleted: boolean;+ /**+ * Why the external deletion failed, when external_deleted is false.+ * @nullable+ */+ error: string | null;+ }+/*** Typed view over the Subscription.delivery_config JSON blob.*/@@ -38183,6 +38269,73 @@ export namespace Schemas {readonly updated_at: string | null;}+ /**+ * * `full_refresh` - full_refresh+ * * `incremental` - incremental+ * * `append` - append+ * * `webhook` - webhook+ * * `cdc` - cdc+ * * `xmin` - xmin+ */+ export type ExternalDataSchemaSyncTypeEnum = typeof ExternalDataSchemaSyncTypeEnum[keyof typeof ExternalDataSchemaSyncTypeEnum];+++ export const ExternalDataSchemaSyncTypeEnum = {+ FullRefresh: 'full_refresh',+ Incremental: 'incremental',+ Append: 'append',+ Webhook: 'webhook',+ Cdc: 'cdc',+ Xmin: 'xmin',+ } as const;++ export interface SimpleExternalDataSchema {+ readonly id: string;+ /** @maxLength 400 */+ name: string;+ /**+ * @maxLength 400+ * @nullable+ */+ label?: string | null;+ should_sync?: boolean;+ /** @nullable */+ last_synced_at?: string | null;+ sync_type?: ExternalDataSchemaSyncTypeEnum | BlankEnum | null;+ }++ export interface ExternalDataJobSerializers {+ readonly id: string;+ readonly created_at: string;+ /** @nullable */+ readonly created_by: number | null;+ /** @nullable */+ readonly finished_at: string | null;+ readonly status: string;+ readonly schema: SimpleExternalDataSchema;+ /** @nullable */+ readonly rows_synced: number | null;+ /**+ * The latest error that occurred during this run.+ * @nullable+ */+ readonly latest_error: string | null;+ /** @nullable */+ readonly workflow_run_id: string | null;+ /**+ * For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob rows produced per sync: `incremental_merge` (consolidated table) vs `scd2_append` (cdc-only history table). `null` for non-CDC syncs. Read from `schema_snapshot`.+ * @nullable+ */+ readonly cdc_write_mode: string | null;+ /**+ * Whether the rows synced by this job count toward billing. `false` for system-initiated runs the customer isn't charged for (e.g. rebuilding a table after an internal issue). `null` on legacy rows and means billable.+ * @nullable+ */+ readonly billable: boolean | null;+ /** Destinations this run delivered to, snapshotted when it started. Empty on runs that predate destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts the rows read from the source once, not once per destination. */+ readonly destination_ids: readonly string[];+ }+/*** @nullable*/@@ -38220,26 +38373,6 @@ export namespace Schemas {readonly supported_api_versions?: string[];} | null;- /**- * * `full_refresh` - full_refresh- * * `incremental` - incremental- * * `append` - append- * * `webhook` - webhook- * * `cdc` - cdc- * * `xmin` - xmin- */- export type ExternalDataSchemaSyncTypeEnum = typeof ExternalDataSchemaSyncTypeEnum[keyof typeof ExternalDataSchemaSyncTypeEnum];--- export const ExternalDataSchemaSyncTypeEnum = {- FullRefresh: 'full_refresh',- Incremental: 'incremental',- Append: 'append',- Webhook: 'webhook',- Cdc: 'cdc',- Xmin: 'xmin',- } as const;-/*** * `integer` - integer* * `numeric` - numeric@@ -92189,6 +92322,11 @@ export namespace Schemas {color?: string | null;}+ export interface UpdateWebhookInputsResponse {+ /** Whether the inputs were saved and pushed to the external service. */+ success: boolean;+ }+export interface UploadVersionRequest {/** Zip archive containing the Streamlit app sources (max 10 MB). */file: string;@@ -93284,6 +93422,101 @@ export namespace Schemas {achievements_opt_out: boolean;}+ export interface WebhookExternalStatus {+ /** Whether the webhook exists on the external service. */+ exists: boolean;+ /**+ * The webhook URL on the external service.+ * @nullable+ */+ url: string | null;+ /**+ * Events the external webhook is subscribed to.+ * @nullable+ */+ enabled_events: string[] | null;+ /**+ * Delivery health as the external service reports it (e.g. 'enabled').+ * @nullable+ */+ status: string | null;+ /**+ * Description the external service holds for it.+ * @nullable+ */+ description: string | null;+ /**+ * When the external webhook was created.+ * @nullable+ */+ created_at: string | null;+ /**+ * Vendor API version the endpoint delivers at, when pinned.+ * @nullable+ */+ api_version: string | null;+ /**+ * Read error the external service returned, if any.+ * @nullable+ */+ error: string | null;+ }++ /**+ * Delivery health reported by the pipeline: `state` and `tokens` counters.+ */+ export type WebhookHogFunctionStatus = { [key: string]: unknown };++ export interface WebhookHogFunction {+ /** ID of the webhook delivery hog function. */+ id: string;+ /** Name of the webhook delivery hog function. */+ name: string;+ /** Whether the webhook delivery function is enabled. */+ enabled: boolean;+ /** When the webhook delivery function was created (ISO 8601). */+ created_at: string;+ /** Delivery health reported by the pipeline: `state` and `tokens` counters. */+ status: WebhookHogFunctionStatus;+ }++ /**+ * Resource name to external schema id, as configured on the webhook function.+ */+ export type WebhookInfoResponseSchemaMapping = {[key: string]: string};++ /**+ * Current webhook function inputs keyed by the source's declared webhook field names.+ */+ export type WebhookInfoResponseInputs = {[key: string]: InputsItem};++ export interface WebhookInfoResponse {+ /** Whether the source type supports webhooks at all. When false, the other fields are absent. */+ supports_webhooks: boolean;+ /** Whether a PostHog webhook delivery function exists for this source yet. */+ exists: boolean;+ /**+ * Set when the connection's credentials can never create the webhook, so only manual setup is left. Null means 'not known to be blocked'.+ * @nullable+ */+ auto_creation_blocked_reason: string | null;+ /** The webhook delivery function, present once the webhook exists. */+ hog_function: WebhookHogFunction | null;+ /**+ * The PostHog endpoint the external service delivers events to.+ * @nullable+ */+ webhook_url: string | null;+ /** Resource name to external schema id, as configured on the webhook function. */+ schema_mapping: WebhookInfoResponseSchemaMapping;+ /** Current webhook function inputs keyed by the source's declared webhook field names. */+ inputs?: WebhookInfoResponseInputs;+ /** Live webhook state as the external service reports it, when it could be read. */+ external_status: WebhookExternalStatus | null;+ /** Desired provider events not yet on the webhook (manual setup, or created before a new table). */+ missing_events?: string[];+ }+export interface WebhookUrl {/** URL to register in Customer.io so it posts subscription changes to PostHog. */url: string;@@ -101509,6 +101742,25 @@ export namespace Schemas {search?: string;};+ export type ExternalDataSourcesJobsListParams = {+ /**+ * ISO timestamp — only return jobs created after this date.+ */+ after?: string;+ /**+ * ISO timestamp — only return jobs created before this date.+ */+ before?: string;+ /**+ * Filter jobs by table schema names.+ */+ schemas?: string[];+ /**+ * A search term.+ */+ search?: string;+ };+export type ExternalDataSourcesRepairCdcCreate200 = {success?: boolean;schemas_reset?: number;@@ -101518,11 +101770,6 @@ export namespace Schemas {success?: boolean;};- export type ExternalDataSourcesCheckCdcPrerequisitesCreate200 = {- valid?: boolean;- errors?: string[];- };-export type ExternalDataSourcesConnectLinkRetrieveParams = {/*** The source type to generate a connect link for (e.g. 'Stripe', 'Postgres', 'Hubspot').diff --git a/services/mcp/src/tools/generated/warehouse_sources.ts b/services/mcp/src/tools/generated/warehouse_sources.tsindex 23a5836c86f8..08d2c015eca2 100644--- a/services/mcp/src/tools/generated/warehouse_sources.ts+++ b/services/mcp/src/tools/generated/warehouse_sources.ts@@ -461,7 +461,7 @@ const ExternalDataSourcesCheckCdcPrerequisitesCreateSchema = () =>const externalDataSourcesCheckCdcPrerequisitesCreate = (): ToolBase<ReturnType<typeof ExternalDataSourcesCheckCdcPrerequisitesCreateSchema>,- unknown+ Schemas.CdcPrerequisitesResponse> => ({name: 'external-data-sources-check-cdc-prerequisites-create',schema: ExternalDataSourcesCheckCdcPrerequisitesCreateSchema(),@@ -474,7 +474,7 @@ const externalDataSourcesCheckCdcPrerequisitesCreate = (): ToolBase<if (params.source_type !== undefined) {body['source_type'] = params.source_type}- const result = await context.api.request<unknown>({+ const result = await context.api.request<Schemas.CdcPrerequisitesResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/check_cdc_prerequisites/`,body,@@ -562,7 +562,7 @@ const ExternalDataSourcesCreateWebhookCreateSchema = () => {const externalDataSourcesCreateWebhookCreate = (): ToolBase<ReturnType<typeof ExternalDataSourcesCreateWebhookCreateSchema>,- unknown+ Schemas.CreateWebhookResponse> => ({name: 'external-data-sources-create-webhook-create',schema: ExternalDataSourcesCreateWebhookCreateSchema(),@@ -599,7 +599,7 @@ const externalDataSourcesCreateWebhookCreate = (): ToolBase<if (params.job_inputs !== undefined) {body['job_inputs'] = params.job_inputs}- const result = await context.api.request<unknown>({+ const result = await context.api.request<Schemas.CreateWebhookResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/create_webhook/`,body,@@ -618,7 +618,7 @@ const ExternalDataSourcesDeleteWebhookCreateSchema = () => {const externalDataSourcesDeleteWebhookCreate = (): ToolBase<ReturnType<typeof ExternalDataSourcesDeleteWebhookCreateSchema>,- unknown+ Schemas.DeleteWebhookResponse> => ({name: 'external-data-sources-delete-webhook-create',schema: ExternalDataSourcesDeleteWebhookCreateSchema(),@@ -655,7 +655,7 @@ const externalDataSourcesDeleteWebhookCreate = (): ToolBase<if (params.job_inputs !== undefined) {body['job_inputs'] = params.job_inputs}- const result = await context.api.request<unknown>({+ const result = await context.api.request<Schemas.DeleteWebhookResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/delete_webhook/`,body,@@ -916,7 +916,7 @@ const ExternalDataSourcesUpdateWebhookInputsCreateSchema = () => {const externalDataSourcesUpdateWebhookInputsCreate = (): ToolBase<ReturnType<typeof ExternalDataSourcesUpdateWebhookInputsCreateSchema>,- unknown+ Schemas.UpdateWebhookInputsResponse> => ({name: 'external-data-sources-update-webhook-inputs-create',schema: ExternalDataSourcesUpdateWebhookInputsCreateSchema(),@@ -953,7 +953,7 @@ const externalDataSourcesUpdateWebhookInputsCreate = (): ToolBase<if (params.job_inputs !== undefined) {body['job_inputs'] = params.job_inputs}- const result = await context.api.request<unknown>({+ const result = await context.api.request<Schemas.UpdateWebhookInputsResponse>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/update_webhook_inputs/`,body,@@ -969,7 +969,7 @@ const ExternalDataSourcesWebhookInfoRetrieveSchema = () => {const externalDataSourcesWebhookInfoRetrieve = (): ToolBase<ReturnType<typeof ExternalDataSourcesWebhookInfoRetrieveSchema>,- unknown+ Schemas.WebhookInfoResponse> => ({name: 'external-data-sources-webhook-info-retrieve',schema: ExternalDataSourcesWebhookInfoRetrieveSchema(),@@ -978,7 +978,7 @@ const externalDataSourcesWebhookInfoRetrieve = (): ToolBase<params: z.infer<ReturnType<typeof ExternalDataSourcesWebhookInfoRetrieveSchema>>) => {const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<unknown>({+ const result = await context.api.request<Schemas.WebhookInfoResponse>({method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_sources/${encodeURIComponent(String(params.id))}/webhook_info/`,})