:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the rudderstack import source (#115491)
Tom Owers4b9f55dc647f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex cf8b870f9432..a7094d335e4b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -703,6 +703,7 @@ the row lists both.| rootly | HTTP | requests | ✅ || rss | HTTP | requests | ✅ || rubygems | HTTP | requests | ✅ |+| rudderstack | HTTP | requests + `rest_source.RESTClient` | ✅ || ruddr | HTTP | requests | ✅ || runpod | HTTP | requests | ✅ || safetyculture | HTTP | requests | ✅ |@@ -1390,7 +1391,6 @@ doesn't conflict with concurrent PRs.- rocket_matter- rocketlane- rss-- rudderstack- safetyculture- sage_intacct- sailthrudiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rudderstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rudderstack.pyindex 67b88d9ed66b..89a68ee2a4ce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rudderstack.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rudderstack.py@@ -1,9 +1,13 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass RudderStackSourceConfig(config.Config):- pass+ access_token: str+ organization_access_token: str | None = None+ region: Literal["us", "eu"] = config.value(default="us")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/canonical_descriptions.pynew file mode 100644index 000000000000..a11b4f637ac2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/canonical_descriptions.py@@ -0,0 +1,111 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sources": {+ "description": "Event sources configured in the RudderStack workspace.",+ "docs_url": "https://github.com/rudderlabs/rudder-iac/blob/main/api/client/sources.go",+ "columns": {"id": "Source identifier.", "name": "Source name.", "createdAt": "Source creation timestamp."},+ },+ "destinations": {+ "description": "Destinations configured to receive RudderStack events.",+ "docs_url": "https://github.com/rudderlabs/rudder-iac/blob/main/api/client/destinations.go",+ "columns": {+ "id": "Destination identifier.",+ "type": "Destination type.",+ "createdAt": "Destination creation timestamp.",+ },+ },+ "connections": {+ "description": "Connections between event sources and destinations.",+ "docs_url": "https://github.com/rudderlabs/rudder-iac/blob/main/api/client/connections.go",+ "columns": {+ "id": "Connection identifier.",+ "sourceId": "Connected source identifier.",+ "destinationId": "Connected destination identifier.",+ },+ },+ "transformations": {+ "description": "Published transformations that change events before delivery.",+ "docs_url": "https://www.rudderstack.com/docs/api/transformation-api/",+ "columns": {+ "id": "Transformation identifier.",+ "versionId": "Published version identifier.",+ "code": "Transformation code.",+ },+ },+ "libraries": {+ "description": "Published code libraries for RudderStack transformations.",+ "docs_url": "https://www.rudderstack.com/docs/api/transformation-api/",+ "columns": {+ "id": "Library identifier.",+ "importName": "Name used to import the library.",+ "code": "Library code.",+ },+ },+ "tracking_plans": {+ "description": "Tracking plans that define the expected event data.",+ "docs_url": "https://www.rudderstack.com/docs/api/data-catalog-api/tracking-plans/",+ "columns": {+ "id": "Tracking plan identifier.",+ "version": "Tracking plan version.",+ "createdAt": "Tracking plan creation timestamp.",+ },+ },+ "catalog_events": {+ "description": "Event definitions in the RudderStack data catalog.",+ "docs_url": "https://www.rudderstack.com/docs/api/data-catalog-api/data-catalog/",+ "columns": {+ "id": "Catalog event identifier.",+ "eventType": "Event type.",+ "categoryId": "Catalog category identifier.",+ },+ },+ "catalog_properties": {+ "description": "Property definitions and validation rules in the data catalog.",+ "docs_url": "https://www.rudderstack.com/docs/api/data-catalog-api/data-catalog/",+ "columns": {+ "id": "Property identifier.",+ "type": "Property data type.",+ "propConfig": "Property validation rules.",+ },+ },+ "catalog_categories": {+ "description": "Categories used to organize catalog events.",+ "docs_url": "https://www.rudderstack.com/docs/api/data-catalog-api/data-catalog/",+ "columns": {+ "id": "Category identifier.",+ "name": "Category name.",+ "createdAt": "Category creation timestamp.",+ },+ },+ "audit_logs": {+ "description": "Organization audit logs. Requires an organization Service Access Token and the Enterprise plan.",+ "docs_url": "https://www.rudderstack.com/docs/api/audit-logs-api/",+ "columns": {+ "id": "Audit log identifier.",+ "createdAt": "Audit log creation timestamp.",+ "action": "Action performed on the target.",+ },+ },+ "retl_connections": {+ "description": "Reverse ETL connections that send warehouse data to destinations.",+ "docs_url": "https://github.com/rudderlabs/rudder-iac/blob/main/api/client/retl/connection_types.go",+ "columns": {+ "id": "Reverse ETL connection identifier.",+ "sourceId": "Connected source identifier.",+ "destinationId": "Connected destination identifier.",+ },+ },+ "retl_syncs": {+ "description": "Reverse ETL sync history, status, and delivery metrics for each connection.",+ "docs_url": "https://www.rudderstack.com/docs/api/retl-connections-api/",+ "columns": {+ "id": "Sync identifier within the connection.",+ "connection_id": "Reverse ETL connection identifier.",+ "startedAt": "Sync start timestamp.",+ "metrics": "Counts of changed, succeeded, and failed records.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/rudderstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/rudderstack.pynew file mode 100644index 000000000000..8fa2b863a0db--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/rudderstack.py@@ -0,0 +1,177 @@+from typing import Any++from requests import Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rudderstack import (+ RudderStackSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.settings import (+ BASE_URLS,+ CATALOG_MAX_PAGES,+ ENDPOINTS,+ RudderStackEndpoint,+)+++@frozen+class RudderStackResumeConfig:+ paginator_state: dict[str, Any]+++class RudderStackCatalogLimitError(ValueError):+ pass+++class RudderStackCatalogPaginator(PageNumberPaginator):+ def __init__(self) -> None:+ super().__init__(base_page=1)++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ payload = response.json()+ total = payload["total"]+ page_size = payload["pageSize"]+ if not isinstance(total, int) or total < 0 or not isinstance(page_size, int) or page_size <= 0:+ raise ValueError("RudderStack returned invalid catalog pagination metadata")+ # The catalog caps requests at 50 pages, so a larger collection cannot produce a complete full refresh.+ if total > page_size * CATALOG_MAX_PAGES:+ raise RudderStackCatalogLimitError("RudderStack catalog exceeds the 50-page API limit")+ super().update_state(response, data)+ if (self.page - 1) * page_size >= total:+ self._has_next_page = False+++def endpoint_config(endpoint: RudderStackEndpoint, api_version: str) -> Endpoint:+ return {+ "path": endpoint.path.replace("/v2/", f"/{api_version}/", 1),+ "data_selector": endpoint.data_selector,+ "data_selector_required": True,+ "params": dict(endpoint.params),+ "paginator": RudderStackCatalogPaginator()+ if endpoint.paginator == "catalog"+ else {"type": "json_response", "next_url_path": "paging.next"}+ if endpoint.paginator == "json_response"+ else "single_page",+ }+++def endpoint_extra(endpoint: RudderStackEndpoint, api_version: str) -> Endpoint:+ config = endpoint_config(endpoint, api_version)+ config.pop("params", None)+ return config+++def token_for_endpoint(config: RudderStackSourceConfig, endpoint: str | None) -> str:+ if endpoint == "audit_logs":+ if not config.organization_access_token:+ raise ValueError("Add an organization Service Access Token to sync audit logs.")+ return config.organization_access_token+ return config.access_token+++def probe_credentials(config: RudderStackSourceConfig, schema_name: str | None, api_version: str) -> int:+ endpoint = schema_for_resource(ENDPOINTS, schema_name) if schema_name else None+ if endpoint and endpoint.fanout:+ endpoint = ENDPOINTS[endpoint.fanout.parent_name]+ path = endpoint.path.replace("/v2/", f"/{api_version}/", 1) if endpoint else f"/{api_version}/workspace"+ token = token_for_endpoint(config, schema_name)+ with make_tracked_session(redact_values=(token,)) as session:+ response = session.get(+ f"{BASE_URLS[config.region]}{path}",+ auth=BearerTokenAuth(token),+ headers={"Accept": "application/json"},+ params=endpoint.params if endpoint else None,+ timeout=(10, 30),+ allow_redirects=False,+ )+ return response.status_code+++def rudderstack_source(+ config: RudderStackSourceConfig,+ inputs: SourceInputs,+ resumable_source_manager: ResumableSourceManager[RudderStackResumeConfig],+ api_version: str,+) -> SourceResponse:+ endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)+ client: ClientConfig = {+ "base_url": BASE_URLS[config.region],+ "auth": {"type": "bearer", "token": token_for_endpoint(config, inputs.schema_name)},+ "headers": {"Accept": "application/json"},+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": (10, 30),+ "retry_budget_seconds": 120,+ "retry_after_max_seconds": 60,+ }+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None:+ resumable_source_manager.save_state(RudderStackResumeConfig(paginator_state=state))++ if endpoint.fanout:+ resource = build_dependent_resource(+ endpoint_configs=ENDPOINTS,+ child_endpoint=inputs.schema_name,+ fanout=endpoint.fanout,+ client_config=client,+ path_format_values={},+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ db_incremental_field_last_value=None,+ page_size_param=None,+ parent_endpoint_extra=endpoint_extra(ENDPOINTS[endpoint.fanout.parent_name], api_version),+ child_endpoint_extra=endpoint_extra(endpoint, api_version),+ resume_hook=save_checkpoint,+ initial_paginator_state=resume.paginator_state if resume else None,+ )+ else:+ rest_config: RESTAPIConfig = {+ "client": client,+ "resources": [+ {+ "name": inputs.schema_name,+ "table_format": "delta",+ "write_disposition": "replace",+ "endpoint": endpoint_config(endpoint, api_version),+ }+ ],+ }+ resource = rest_api_resource(+ rest_config,+ inputs.team_id,+ inputs.job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=resume.paginator_state if resume else None,+ )+ return SourceResponse(+ name=inputs.schema_name,+ items=lambda: resource,+ primary_keys=list(endpoint.primary_keys),+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint.partition_key],+ sort_mode=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/settings.pynew file mode 100644index 000000000000..23202d0ceac2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/settings.py@@ -0,0 +1,96 @@+from dataclasses import field+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++BASE_URLS = {+ "us": "https://api.rudderstack.com",+ "eu": "https://api.eu.rudderstack.com",+}+CATALOG_MAX_PAGES = 50+++@frozen+class RudderStackEndpoint:+ name: str+ path: str+ data_selector: str+ paginator: Literal["single_page", "json_response", "catalog"] = "json_response"+ primary_keys: tuple[str, ...] = ("id",)+ partition_key: str = "createdAt"+ params: dict[str, str | int] = field(default_factory=dict)+ fanout: DependentEndpointConfig | None = None+ page_size: int = 100+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+++# Timestamp filters for audit logs and sync history need account verification before enabling incremental sync.+ENDPOINTS: dict[str, RudderStackEndpoint] = {+ "sources": RudderStackEndpoint(name="sources", path="/v2/sources", data_selector="sources"),+ "destinations": RudderStackEndpoint(name="destinations", path="/v2/destinations", data_selector="destinations"),+ "connections": RudderStackEndpoint(name="connections", path="/v2/connections", data_selector="connections"),+ "transformations": RudderStackEndpoint(+ name="transformations", path="/transformations", data_selector="transformations", paginator="single_page"+ ),+ "libraries": RudderStackEndpoint(+ name="libraries", path="/libraries", data_selector="libraries", paginator="single_page"+ ),+ "tracking_plans": RudderStackEndpoint(+ name="tracking_plans", path="/v2/catalog/tracking-plans", data_selector="trackingPlans", paginator="single_page"+ ),+ "catalog_events": RudderStackEndpoint(+ name="catalog_events",+ path="/v2/catalog/events",+ data_selector="data",+ paginator="catalog",+ params={"orderBy": "createdAt:asc"},+ ),+ "catalog_properties": RudderStackEndpoint(+ name="catalog_properties",+ path="/v2/catalog/properties",+ data_selector="data",+ paginator="catalog",+ params={"orderBy": "createdAt:asc"},+ ),+ "catalog_categories": RudderStackEndpoint(+ name="catalog_categories",+ path="/v2/catalog/categories",+ data_selector="data",+ paginator="catalog",+ params={"orderBy": "createdAt:asc"},+ ),+ "audit_logs": RudderStackEndpoint(+ name="audit_logs",+ path="/v2/audit-logs",+ data_selector="data",+ params={"per_page": 100},+ ),+ "retl_connections": RudderStackEndpoint(+ name="retl_connections",+ path="/v2/retl-connections",+ data_selector="data",+ params={"pageSize": 100},+ ),+ "retl_syncs": RudderStackEndpoint(+ name="retl_syncs",+ path="/v2/retl-connections/{connection_id}/syncs",+ data_selector="syncs",+ primary_keys=("connection_id", "id"),+ partition_key="startedAt",+ fanout=DependentEndpointConfig(+ parent_name="retl_connections",+ resolve_param="connection_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "connection_id"},+ parent_params={"pageSize": 100},+ child_params={"per_page": 100},+ ),+ ),+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/source.pyindex 594dc3f935b7..1903687c0ac3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/source.py@@ -1,16 +1,50 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests.exceptions import RequestException++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rudderstack import (RudderStackSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.rudderstack import (+ RudderStackResumeConfig,+ probe_credentials,+ rudderstack_source,+ token_for_endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.settings import BASE_URLS, ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RudderStackSource(SimpleSource[RudderStackSourceConfig]):+class RudderStackSource(ResumableSource[RudderStackSourceConfig, RudderStackResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://www.rudderstack.com/docs/api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RUDDERSTACK@@ -21,8 +55,125 @@ class RudderStackSource(SimpleSource[RudderStackSourceConfig]):name=ExternalDataSourceType.RUDDERSTACK,category=DataWarehouseSourceCategory.ANALYTICS,label="RudderStack",+ docsUrl="https://posthog.com/docs/cdp/sources/rudderstack",iconPath="/static/services/rudderstack.png",keywords=["cdp", "customer data platform", "event streaming"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Workspace access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ placeholder="",+ caption="Use a workspace Service Access Token with read access to the selected resources. "+ "A Personal Access Token also works.",+ ),+ SourceFieldInputConfig(+ name="organization_access_token",+ label="Organization access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ secret=True,+ placeholder="",+ caption="Optional. Audit logs require an organization Service Access Token and the RudderStack Enterprise plan.",+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US", value="us"),+ SourceFieldSelectConfigOption(label="EU", value="eu"),+ ],+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "RudderStack rejected the access token. Replace the invalid or expired token.",+ "403 Client Error": "RudderStack denied access to this table. Check the token permissions and account plan.",+ "Add an organization Service Access Token": "Add an organization Service Access Token to sync audit logs.",+ "RudderStack catalog exceeds": "The catalog exceeds the RudderStack 50-page API limit. Contact RudderStack support.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: RudderStackSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ {},+ names,+ descriptions={name: description["description"] for name, description in CANONICAL_DESCRIPTIONS.items()},+ should_sync_default={"audit_logs": False, "retl_connections": False, "retl_syncs": False},+ )++ def get_endpoint_permissions(+ self,+ config: RudderStackSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ return {+ name: "Add an organization Service Access Token to sync audit logs."+ if name == "audit_logs" and not config.organization_access_token+ else None+ for name in endpoints+ }++ def validate_credentials(+ self,+ config: RudderStackSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if config.region not in BASE_URLS:+ return False, "Select the US or EU region for your RudderStack account."+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, "This RudderStack table is not supported."+ try:+ token = token_for_endpoint(config, schema_name)+ if not token or not token.isascii() or any(character.isspace() for character in token):+ return False, "Enter a valid RudderStack access token without spaces."+ status = probe_credentials(config, schema_name, self.resolve_api_version(api_version))+ except ValueError as error:+ return False, str(error)+ except RequestException:+ return False, "Could not connect to RudderStack. Try again."+ if status == 200 or (status == 403 and schema_name is None):+ return True, None+ if status == 401:+ return False, "RudderStack rejected the access token. Replace the invalid or expired token."+ if status == 403:+ return False, "RudderStack denied access to this table. Check the token permissions and account plan."+ return False, f"RudderStack returned HTTP {status}. Try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RudderStackResumeConfig]:+ return ResumableSourceManager(inputs, RudderStackResumeConfig)++ def source_for_pipeline(+ self,+ config: RudderStackSourceConfig,+ resumable_source_manager: ResumableSourceManager[RudderStackResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return rudderstack_source(+ config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/tests/test_rudderstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/tests/test_rudderstack.pynew file mode 100644index 000000000000..fad03e5de789--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/tests/test_rudderstack.py@@ -0,0 +1,222 @@+from typing import Any++import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rudderstack import (+ RudderStackSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.rudderstack import (+ RudderStackCatalogLimitError,+ RudderStackResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.source import RudderStackSource+++def driver() -> SourceDriver:+ return SourceDriver(+ RudderStackSource(),+ RudderStackSourceConfig(+ access_token="test-workspace-token", organization_access_token="test-organization-token"+ ),+ )+++ ("table", "path", "selector", "page_param", "token"),+ [+ ("sources", "/v2/sources", "sources", "page", "test-workspace-token"),+ ("destinations", "/v2/destinations", "destinations", "page", "test-workspace-token"),+ ("connections", "/v2/connections", "connections", "page", "test-workspace-token"),+ ("retl_connections", "/v2/retl-connections", "data", "page", "test-workspace-token"),+ ("audit_logs", "/v2/audit-logs", "data", "after_cursor", "test-organization-token"),+ ],+)+def test_linked_collections_walk_to_the_end_and_commit_resume_state(+ driver: SourceDriver,+ table: str,+ path: str,+ selector: str,+ page_param: str,+ token: str,+) -> None:+ next_path = f"{path}?{page_param}=next-page"+ result = driver.run(+ table,+ [+ ScriptedResponse(json={selector: [{"id": "row-a"}], "paging": {"next": next_path}}),+ ScriptedResponse(json={selector: [{"id": "row-b"}], "paging": {"next": ""}}),+ ],+ )++ assert result.raised is None+ assert result.rows == [{"id": "row-a"}, {"id": "row-b"}]+ assert result.paths == [path, path]+ assert result.params(page_param) == [None, "next-page"]+ assert all(request.headers["authorization"] == f"Bearer {token}" for request in result.requests)+ assert result.committed_states == [+ RudderStackResumeConfig(paginator_state={"next_url": f"https://api.rudderstack.com{next_path}"})+ ]+ assert all(request.param("created_after") is None for request in result.requests)++[email protected]("table", ["catalog_events", "catalog_properties", "catalog_categories"])+def test_catalog_uses_response_page_size_and_stops_at_total(driver: SourceDriver, table: str) -> None:+ result = driver.run(+ table,+ [+ ScriptedResponse(json={"data": [{"id": "a"}, {"id": "b"}], "total": 3, "pageSize": 2, "currentPage": 1}),+ ScriptedResponse(json={"data": [{"id": "c"}], "total": 3, "pageSize": 2, "currentPage": 2}),+ ],+ )++ assert result.raised is None+ assert result.rows == [{"id": "a"}, {"id": "b"}, {"id": "c"}]+ assert result.params("page") == ["1", "2"]+ assert result.params("orderBy") == ["createdAt:asc", "createdAt:asc"]+ assert result.committed_states == [RudderStackResumeConfig(paginator_state={"page": 2})]+++ ("payload", "error_type"),+ [+ ({"data": [{"id": "a"}], "total": 2501, "pageSize": 50}, RudderStackCatalogLimitError),+ ({"data": [{"id": "a"}], "total": 1, "pageSize": 0}, ValueError),+ ],+)+def test_catalog_refuses_incomplete_or_invalid_pagination(+ driver: SourceDriver,+ payload: dict[str, Any],+ error_type: type[Exception],+) -> None:+ result = driver.run("catalog_events", [ScriptedResponse(json=payload)])++ assert isinstance(result.raised, error_type)+ assert result.rows == []+ assert result.committed_states == []+++ ("table", "selector", "path"),+ [+ ("transformations", "transformations", "/transformations"),+ ("libraries", "libraries", "/libraries"),+ ("tracking_plans", "trackingPlans", "/v2/catalog/tracking-plans"),+ ],+)+def test_unpaginated_collections_preserve_vendor_rows(+ driver: SourceDriver,+ table: str,+ selector: str,+ path: str,+) -> None:+ rows = [{"id": "a", "description": None, "config": {"nested": ["value"]}}, {"id": "b"}]+ result = driver.run(table, [ScriptedResponse(json={selector: rows})])++ assert result.raised is None+ assert result.rows == rows+ assert result.paths == [path]+++ ("table", "state", "payload", "path", "param", "value"),+ [+ (+ "audit_logs",+ {"next_url": "https://api.rudderstack.com/v2/audit-logs?after_cursor=saved&per_page=100"},+ {"data": [{"id": "last"}], "paging": {}},+ "/v2/audit-logs",+ "after_cursor",+ "saved",+ ),+ (+ "catalog_properties",+ {"page": 2},+ {"data": [{"id": "last"}], "total": 3, "pageSize": 2},+ "/v2/catalog/properties",+ "page",+ "2",+ ),+ ],+)+def test_resume_starts_after_the_last_written_page(+ driver: SourceDriver,+ table: str,+ state: dict[str, Any],+ payload: dict[str, Any],+ path: str,+ param: str,+ value: str,+) -> None:+ result = driver.run(+ table, [ScriptedResponse(json=payload)], resume_state=RudderStackResumeConfig(paginator_state=state)+ )++ assert result.raised is None+ assert result.paths == [path]+ assert result.params(param) == [value]+ assert result.rows == [{"id": "last"}]+++def test_sync_history_fans_out_and_preserves_the_connection_for_each_sync(driver: SourceDriver) -> None:+ first_path = "/v2/retl-connections/connection-a/syncs"+ result = driver.run(+ "retl_syncs",+ [+ ScriptedResponse(json={"data": [{"id": "connection-a"}, {"id": "connection-b"}], "paging": {}}),+ ScriptedResponse(+ json={+ "syncs": [{"id": "shared-id", "metrics": {"total": 2}}],+ "paging": {"next": f"{first_path}?page=2&per_page=100"},+ }+ ),+ ScriptedResponse(json={"syncs": [{"id": "last-a"}], "paging": {}}),+ ScriptedResponse(json={"syncs": [{"id": "shared-id", "metrics": {"total": 5}}], "paging": {}}),+ ],+ )++ assert result.raised is None+ assert result.rows == [+ {"id": "shared-id", "metrics": {"total": 2}, "connection_id": "connection-a"},+ {"id": "last-a", "connection_id": "connection-a"},+ {"id": "shared-id", "metrics": {"total": 5}, "connection_id": "connection-b"},+ ]+ assert result.paths == ["/v2/retl-connections", first_path, first_path, "/v2/retl-connections/connection-b/syncs"]+ assert result.params("per_page") == [None, "100", "100", "100"]+ assert all(request.param("started_after") is None for request in result.requests)+ assert result.committed_states+++def test_sync_history_resume_skips_completed_connections(driver: SourceDriver) -> None:+ result = driver.run(+ "retl_syncs",+ [+ ScriptedResponse(json={"data": [{"id": "connection-a"}, {"id": "connection-b"}], "paging": {}}),+ ScriptedResponse(json={"syncs": [{"id": "remaining"}], "paging": {}}),+ ],+ resume_state=RudderStackResumeConfig(+ paginator_state={+ "completed": ["/v2/retl-connections/connection-a/syncs"],+ "current": None,+ "child_state": None,+ }+ ),+ )++ assert result.raised is None+ assert result.paths == ["/v2/retl-connections", "/v2/retl-connections/connection-b/syncs"]+ assert result.rows == [{"id": "remaining", "connection_id": "connection-b"}]++[email protected]("status", [401, 403])+def test_auth_failures_from_transport_match_permanent_error_messages(driver: SourceDriver, status: int) -> None:+ result = driver.run("sources", [ScriptedResponse(status=status, json={"message": "Unauthorized"})])++ assert result.raised is not None+ assert error_message_matches(str(result.raised), RudderStackSource().get_non_retryable_errors())+ assert result.rows == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/tests/test_rudderstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/tests/test_rudderstack_source.pynew file mode 100644index 000000000000..be81b4aac222--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rudderstack/tests/test_rudderstack_source.py@@ -0,0 +1,73 @@+import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.rudderstack import (+ RudderStackSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.rudderstack.source import RudderStackSource+++ ("schema_name", "status", "expected", "path", "token"),+ [+ (None, 200, True, "/v2/workspace", "test-workspace-token"),+ (None, 403, True, "/v2/workspace", "test-workspace-token"),+ (None, 401, False, "/v2/workspace", "test-workspace-token"),+ ("sources", 403, False, "/v2/sources", "test-workspace-token"),+ ("audit_logs", 200, True, "/v2/audit-logs", "test-organization-token"),+ ("retl_syncs", 200, True, "/v2/retl-connections", "test-workspace-token"),+ (None, 400, False, "/v2/workspace", "test-workspace-token"),+ ],+)+def test_credential_probes_select_token_and_allow_missing_scope_only_at_creation(+ schema_name: str | None,+ status: int,+ expected: bool,+ path: str,+ token: str,+) -> None:+ config = RudderStackSourceConfig(+ access_token="test-workspace-token",+ organization_access_token="test-organization-token",+ region="eu",+ )+ with scripted_network([ScriptedResponse(status=status, json={"message": "Unauthorized"})]) as network:+ valid, message = RudderStackSource().validate_credentials(config, team_id=1, schema_name=schema_name)++ assert valid is expected+ assert bool(message) is not expected+ assert len(network.requests_log) == 1+ request = network.requests_log[0]+ assert request.path == path+ assert request.origin == "https://api.eu.rudderstack.com"+ assert request.headers["authorization"] == f"Bearer {token}"+++ ("token", "schema_name", "expected_message"),+ [+ ("", None, "Enter a valid"),+ ("token\nvalue", None, "Enter a valid"),+ ("tökén", None, "Enter a valid"),+ ("test-token", "unknown", "not supported"),+ ("test-token", "audit_logs", "organization Service Access Token"),+ ],+)+def test_invalid_configuration_fails_without_sending_a_request(+ token: str,+ schema_name: str | None,+ expected_message: str,+) -> None:+ with scripted_network([]) as network:+ valid, message = RudderStackSource().validate_credentials(+ RudderStackSourceConfig(access_token=token),+ team_id=1,+ schema_name=schema_name,+ )++ assert not valid+ assert message is not None and expected_message in message+ assert network.requests_log == []