: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 acast import source (#111827)
Tom Owersa5f363f3dc4b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 7a5e1a26fe6f..be966b26f875 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -51,6 +51,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || ably | HTTP | requests + `rest_source.RESTClient` | ✅ |+| acast | HTTP | requests | ✅ || acculynx | HTTP | requests + `rest_source.RESTClient` | ✅ || adjust | HTTP | requests | ✅ || adobe_analytics | HTTP | requests | ✅ |@@ -884,7 +885,6 @@ doesn't conflict with concurrent PRs.- \*\*Switch- ab_tasty- abnormal_security-- acast- actionstep- active_campaign- acuity_schedulingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/acast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/acast.pynew file mode 100644index 000000000000..e62e8a3e4a81--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/acast.py@@ -0,0 +1,71 @@+from collections.abc import Iterable+from typing import Any, cast++from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.acast.settings import (+ AUTH_ERROR,+ BASE_URL,+ ENDPOINTS,+ PERMISSION_ERROR,+ PRIMARY_KEYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ EndpointResource,+ RESTAPIConfig,+ rest_api_resources,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ rename_parent_fields,+)+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 SourceResponse+++def acast_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:+ endpoint_config = schema_for_resource(ENDPOINTS, endpoint)+ resources: list[str | EndpointResource] = (+ [ENDPOINTS["shows"], endpoint_config] if endpoint == "episodes" else [endpoint_config]+ )+ config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {"type": "api_key", "name": "X-API-Key", "api_key": api_key, "location": "header"},+ "paginator": "single_page",+ "allow_redirects": False,+ "request_timeout": 60,+ },+ "resource_defaults": {+ "write_disposition": "replace",+ "endpoint": {"data_selector": "", "data_selector_required": True},+ },+ "resources": resources,+ }+ resource = next(+ resource+ for resource in rest_api_resources(config, team_id, job_id, db_incremental_field_last_value=None)+ if resource.name == endpoint+ )+ if endpoint == "episodes":+ resource.add_map(rename_parent_fields("shows", {"_id": "show_id"}))++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=PRIMARY_KEYS[endpoint],+ sort_mode=None,+ )+++def validate_credentials(api_key: str, team_id: int) -> tuple[bool, str | None]:+ try:+ items = cast(Iterable[Any], acast_source(api_key, "shows", team_id, "").items())+ next(iter(items), None)+ except HTTPError as error:+ if error.response is not None:+ if error.response.status_code == 401:+ return False, AUTH_ERROR+ if error.response.status_code == 403:+ return False, PERMISSION_ERROR+ raise+ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/canonical_descriptions.pynew file mode 100644index 000000000000..27c5bb842eac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/canonical_descriptions.py@@ -0,0 +1,40 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "shows": {+ "description": "Podcast shows assigned to the user who owns the Acast API key.",+ "docs_url": "https://developers.acast.com/",+ "columns": {+ "_id": "The unique identifier for the show.",+ "title": "The title of the show.",+ "summary": "The description of the show, including HTML formatting.",+ "creationDate": "The date and time when the show was created.",+ "publishDate": "The publication date and time of the show.",+ "episodesCount": "The number of episodes in the show.",+ "isPrivate": "Whether the show is private.",+ "Lang": "The language of the show.",+ "Status": "The publication status of the show.",+ },+ },+ "episodes": {+ "description": "Podcast episodes for each show assigned to the user who owns the Acast API key.",+ "docs_url": "https://developers.acast.com/",+ "columns": {+ "_id": "The identifier for the episode.",+ "show_id": "The identifier of the parent show, added during import.",+ "Show": "The identifier of the show that contains the episode.",+ "title": "The title of the episode.",+ "summary": "The description of the episode, including HTML formatting.",+ "creationDate": "The date and time when the episode was created.",+ "lastEditedDate": "The date and time when the episode was last edited.",+ "publishDate": "The publication date and time of the episode.",+ "Status": "The publication status of the episode.",+ "Duration": "The duration of the episode in seconds.",+ "episodeNumber": "The episode number within the show.",+ "Season": "The season number of the episode.",+ "Markers": "Advertisement markers with their identifiers, placements, and start times.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/settings.pynew file mode 100644index 000000000000..b9d780d33d70--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/settings.py@@ -0,0 +1,23 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource++BASE_URL = "https://open.acast.com/rest/"++ENDPOINTS: dict[str, EndpointResource] = {+ "shows": {+ "name": "shows",+ "endpoint": {"path": "shows"},+ },+ "episodes": {+ "name": "episodes",+ "include_from_parent": ["_id"],+ "endpoint": {+ "path": "shows/{show_id}/episodes",+ "params": {"show_id": {"type": "resolve", "resource": "shows", "field": "_id"}},+ },+ },+}++PRIMARY_KEYS = {"shows": ["_id"], "episodes": ["show_id", "_id"]}++AUTH_ERROR = "Acast rejected the API key. Contact Acast Customer Success to check or replace the key."+PERMISSION_ERROR = "Acast denied access. Ask Acast Customer Success to check the shows assigned to your API key."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/source.pyindex 7683bfe640cf..8c1253423e98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/source.py@@ -1,14 +1,43 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.acast.acast import (+ acast_source,+ validate_credentials as validate_acast_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.acast.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.acast.settings import (+ AUTH_ERROR,+ ENDPOINTS,+ PERMISSION_ERROR,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.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.acast import AcastSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass AcastSource(SimpleSource[AcastSourceConfig]):+ lists_tables_without_credentials = True+ api_docs_url = "https://developers.acast.com/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ACAST@@ -20,6 +49,52 @@ class AcastSource(SimpleSource[AcastSourceConfig]):category=DataWarehouseSourceCategory.ADVERTISING,label="Acast",iconPath="/static/services/acast.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption=(+ "Request an API key from Acast Customer Success through the Acast chat box. "+ "API access requires the Pro plan or Creator Network membership. "+ "The key can read shows assigned to its user."+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ )+ ],+ ),)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {"401 Client Error": AUTH_ERROR, "403 Client Error": PERMISSION_ERROR}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AcastSourceConfig,+ 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)++ def validate_credentials(+ self,+ config: AcastSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_acast_credentials(config.api_key, team_id)++ def source_for_pipeline(self, config: AcastSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return acast_source(config.api_key, inputs.schema_name, inputs.team_id, inputs.job_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.pynew file mode 100644index 000000000000..45bdd5080ecd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acast/tests/test_acast.py@@ -0,0 +1,170 @@+import json+from collections.abc import Iterable, Iterator+from http import HTTPStatus+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.acast.acast import (+ acast_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.acast.source import AcastSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+++def items(response: SourceResponse) -> Iterable[Any]:+ return cast(Iterable[Any], response.items())+++def response(body: object, status: int = 200) -> Response:+ result = Response()+ result.status_code = status+ result.reason = HTTPStatus(status).phrase+ result.url = "https://open.acast.com/rest/shows"+ result.headers["Content-Type"] = "application/json"+ result._content = json.dumps(body).encode()+ return result+++def http_session() -> Iterator[MagicMock]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as factory:+ session = factory.return_value+ session.headers = {}+ session.prepare_request.side_effect = Request.prepare+ yield session++[email protected]("rows", [[], [{"_id": "show-1"}], [{"_id": "show-1"}, {"_id": "show-2"}]])+def test_shows_full_refresh_stops_after_one_response(http_session: MagicMock, rows: list[dict[str, str]]) -> None:+ http_session.send.side_effect = [response(rows)]++ result = acast_source("fake-acast-key", "shows", 1, "job-1")+ assert [row for batch in items(result) for row in batch] == rows+ http_session.send.assert_called_once()+ request = http_session.send.call_args.args[0]+ assert request.method == "GET"+ assert request.url == "https://open.acast.com/rest/shows"+ assert request.headers["X-API-Key"] == "fake-acast-key"+ assert "Authorization" not in request.headers+++def test_episode_fanout_keeps_parent_keys_and_continues_after_empty_show(http_session: MagicMock) -> None:+ http_session.send.side_effect = [+ response([{"_id": "show-1"}, {"_id": "show-2"}, {"_id": "show-3"}]),+ response([{"_id": "episode-1", "title": "First episode", "Markers": []}]),+ response([]),+ response([{"_id": "episode-1", "title": "Another episode", "Markers": []}]),+ ]++ result = acast_source("fake-acast-key", "episodes", 1, "job-1")+ rows = [row for batch in items(result) for row in batch]++ assert rows == [+ {"_id": "episode-1", "title": "First episode", "Markers": [], "show_id": "show-1"},+ {"_id": "episode-1", "title": "Another episode", "Markers": [], "show_id": "show-3"},+ ]+ assert result.primary_keys is not None+ assert len({tuple(row[key] for key in result.primary_keys) for row in rows}) == 2+ requests = [call.args[0] for call in http_session.send.call_args_list]+ assert [request.url for request in requests] == [+ "https://open.acast.com/rest/shows",+ "https://open.acast.com/rest/shows/show-1/episodes",+ "https://open.acast.com/rest/shows/show-2/episodes",+ "https://open.acast.com/rest/shows/show-3/episodes",+ ]+ assert all(request.headers["X-API-Key"] == "fake-acast-key" for request in requests)+++def test_episodes_with_no_shows_make_no_child_requests(http_session: MagicMock) -> None:+ http_session.send.side_effect = [response([])]++ assert list(items(acast_source("fake-acast-key", "episodes", 1, "job-1"))) == []+ http_session.send.assert_called_once()+++ ("status", "message", "expected"),+ [+ (200, "", (True, None)),+ (+ 401,+ "Authentication required",+ (False, "Acast rejected the API key. Contact Acast Customer Success to check or replace the key."),+ ),+ (+ 403,+ "Forbidden",+ (False, "Acast denied access. Ask Acast Customer Success to check the shows assigned to your API key."),+ ),+ ],+)+def test_credential_validation_maps_auth_errors(+ http_session: MagicMock, status: int, message: str, expected: tuple[bool, str | None]+) -> None:+ http_session.send.side_effect = [+ response([] if status == 200 else {"statusCode": status, "message": message}, status)+ ]++ assert validate_credentials("fake-acast-key", 1) == expected+ http_session.send.assert_called_once()+ request = http_session.send.call_args.args[0]+ assert request.url == "https://open.acast.com/rest/shows"+ assert request.headers["X-API-Key"] == "fake-acast-key"++[email protected]("status", [401, 403, 404])+def test_sync_errors_are_not_retried_and_auth_errors_match_user_messages(http_session: MagicMock, status: int) -> None:+ http_session.send.side_effect = [response({"statusCode": status}, status)]++ with pytest.raises(HTTPError) as error:+ list(items(acast_source("fake-acast-key", "shows", 1, "job-1")))++ http_session.send.assert_called_once()+ matches = [+ message for pattern, message in AcastSource().get_non_retryable_errors().items() if pattern in str(error.value)+ ]+ assert len(matches) == (0 if status == 404 else 1)+ assert "fake-acast-key" not in str(error.value)+++def test_credential_validation_propagates_other_errors(http_session: MagicMock) -> None:+ http_session.send.side_effect = [response({"statusCode": 404}, 404)]++ with pytest.raises(HTTPError):+ validate_credentials("fake-acast-key", 1)++[email protected]("status", [429, 500, 503])+def test_transient_errors_use_framework_retries(http_session: MagicMock, status: int) -> None:+ failed_response = response({"statusCode": status}, status)+ failed_response.headers["Retry-After"] = "0"+ http_session.send.side_effect = [failed_response, response([{"_id": "show-1"}])]++ with patch("time.sleep"):+ rows = [row for batch in items(acast_source("fake-acast-key", "shows", 1, "job-1")) for row in batch]++ assert rows == [{"_id": "show-1"}]+ assert http_session.send.call_count == 2+++def test_unexpected_response_shape_fails_instead_of_importing_an_error(http_session: MagicMock) -> None:+ http_session.send.side_effect = [response({"error": "Unexpected response"})]++ with pytest.raises(ValueError, match="Required a list response body"):+ list(items(acast_source("fake-acast-key", "shows", 1, "job-1")))+++def test_unknown_table_fails_before_making_requests(http_session: MagicMock) -> None:+ with pytest.raises(UnknownResourceError):+ acast_source("fake-acast-key", "unknown", 1, "job-1")++ http_session.send.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/acast.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/acast.pyindex 20341fb2cd78..95cd3b3e2c48 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/acast.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/acast.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AcastSourceConfig(config.Config):- pass+ api_key: str