Skip to content

: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.

feat(data-warehouse): add Transistor.fm source (#77106)

Tom Owers9bb8269252b8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 7cbe7d83c9ba..477d8d0e5bd3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -627,6 +627,7 @@ the row lists both.
| todoist | HTTP | requests | ✅ |
| together_ai | HTTP | requests | ✅ |
| torii | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| transistor | HTTP | requests | ✅ |
| travis_ci | HTTP | requests | ✅ |
| trello | HTTP | requests | ✅ |
| tremendous | HTTP | requests | ✅ |
@@ -1372,7 +1373,6 @@ doesn't conflict with concurrent PRs.
- toggl
- track_pms
- tradable_bits
-- transistor
- tremendous
- triple_whale
- trustpilot
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/transistor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/transistor.py
index 64fccb0609d4..6ab556861df1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/transistor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/transistor.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class TransistorSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/canonical_descriptions.py
new file mode 100644
index 000000000000..4c881b9474ee
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/canonical_descriptions.py
@@ -0,0 +1,124 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_SHOWS_DOCS = "https://developers.transistor.fm/#/Shows"
+_EPISODES_DOCS = "https://developers.transistor.fm/#/Episodes"
+_SUBSCRIBERS_DOCS = "https://developers.transistor.fm/#/Subscribers"
+_WEBHOOKS_DOCS = "https://developers.transistor.fm/#/Webhooks"
+_ANALYTICS_DOCS = "https://developers.transistor.fm/#/Analytics"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "shows": {
+ "description": "Podcasts on the Transistor account, one row per show.",
+ "docs_url": _SHOWS_DOCS,
+ "columns": {
+ "id": "Unique identifier for the show.",
+ "type": "JSON:API resource type, always `show`.",
+ "title": "Name of the podcast.",
+ "description": "Description of the podcast, shown in podcast apps.",
+ "author": "Author credited in the podcast feed.",
+ "category": "Primary Apple Podcasts category.",
+ "secondary_category": "Secondary Apple Podcasts category.",
+ "copyright": "Copyright line published in the feed.",
+ "created_at": "When the show was created.",
+ "updated_at": "When the show was last updated.",
+ "explicit": "Whether the show is marked as containing explicit content.",
+ "image_url": "URL of the show artwork.",
+ "keywords": "Comma-separated keywords published in the feed.",
+ "language": "Language code of the show.",
+ "private": "Whether the show is a private podcast, which is what makes subscribers apply.",
+ "show_type": "Show format, one of episodic or serial.",
+ "slug": "URL-safe identifier used in Transistor web addresses.",
+ "time_zone": "Time zone used when scheduling episodes.",
+ "website": "Website linked from the podcast feed.",
+ "feed_url": "Public RSS feed URL for the show.",
+ "email_notifications": "Whether Transistor emails subscribers when a new episode publishes.",
+ "playlist_limit": "Number of episodes kept in the feed, when the show limits it.",
+ },
+ },
+ "episodes": {
+ "description": "Episodes across every show on the account, including drafts and scheduled episodes.",
+ "docs_url": _EPISODES_DOCS,
+ "columns": {
+ "id": "Unique identifier for the episode.",
+ "type": "JSON:API resource type, always `episode`.",
+ "show_id": "Identifier of the show the episode belongs to.",
+ "title": "Episode title.",
+ "number": "Episode number within its season.",
+ "season": "Season number the episode belongs to.",
+ "status": "Publishing state, one of draft, scheduled, or published.",
+ "published_at": "When the episode was published, or is scheduled to publish.",
+ "duration": "Length of the episode audio in seconds.",
+ "explicit": "Whether the episode is marked as containing explicit content.",
+ "keywords": "Comma-separated keywords published in the feed.",
+ "media_url": "URL of the episode audio file.",
+ "image_url": "URL of the episode artwork.",
+ "video_url": "URL of the episode video, when one is set.",
+ "author": "Author credited for the episode.",
+ "summary": "Short summary of the episode.",
+ "description": "Full episode description, shown in podcast apps.",
+ "slug": "URL-safe identifier used in Transistor web addresses.",
+ "created_at": "When the episode was created.",
+ "updated_at": "When the episode was last updated.",
+ "share_url": "Public Transistor page for the episode.",
+ "transcript_url": "URL of the episode transcript, when one exists.",
+ "embed_html": "HTML snippet that embeds the episode player.",
+ "embed_html_dark": "HTML snippet that embeds the dark-theme episode player.",
+ "audio_processing": "Whether Transistor is still processing the uploaded audio.",
+ },
+ },
+ "subscribers": {
+ "description": "Private podcast subscribers, one row per subscriber per show.",
+ "docs_url": _SUBSCRIBERS_DOCS,
+ "columns": {
+ "id": "Unique identifier for the subscriber.",
+ "type": "JSON:API resource type, always `subscriber`.",
+ "show_id": "Identifier of the private show the subscriber is subscribed to.",
+ "email": "Email address the private feed was issued to.",
+ "status": "Subscription state reported by Transistor.",
+ "feed_url": "Private RSS feed URL issued to this subscriber.",
+ "subscribe_url": "Link the subscriber uses to add the private feed to a podcast app.",
+ "created_at": "When the subscriber was added.",
+ "updated_at": "When the subscriber was last updated.",
+ "last_notified_at": "When Transistor last emailed the subscriber about a new episode.",
+ "has_downloads": "Whether any downloads have been recorded against this subscriber's feed.",
+ },
+ },
+ "webhooks": {
+ "description": "Webhook subscriptions registered on each show.",
+ "docs_url": _WEBHOOKS_DOCS,
+ "columns": {
+ "id": "Unique identifier for the webhook subscription.",
+ "type": "JSON:API resource type, always `webhook`.",
+ "show_id": "Identifier of the show the webhook is registered on.",
+ "event_name": "Event the webhook fires on: episode_created, episode_published, subscriber_created, or subscriber_deleted.",
+ "url": "URL Transistor posts the event to.",
+ "created_at": "When the webhook was created.",
+ "updated_at": "When the webhook was last updated.",
+ },
+ },
+ "show_analytics": {
+ "description": "Daily download counts per show, one row per show per day.",
+ "docs_url": _ANALYTICS_DOCS,
+ "columns": {
+ "show_id": "Identifier of the show the downloads belong to.",
+ "date": "Day the downloads were recorded, as an ISO `YYYY-MM-DD` date.",
+ "raw_date": "Date exactly as the Transistor API returned it, before parsing.",
+ "downloads": "Number of downloads recorded for the show on that day.",
+ },
+ },
+ "episode_analytics": {
+ "description": "Daily download counts per episode, one row per episode per day.",
+ "docs_url": _ANALYTICS_DOCS,
+ "columns": {
+ "show_id": "Identifier of the show the episode belongs to.",
+ "episode_id": "Identifier of the episode, as reported by the analytics endpoint.",
+ "episode_title": "Title of the episode at the time analytics were fetched.",
+ "episode_published_at": "When the episode was published.",
+ "date": "Day the downloads were recorded, as an ISO `YYYY-MM-DD` date.",
+ "raw_date": "Date exactly as the Transistor API returned it, before parsing.",
+ "downloads": "Number of downloads recorded for the episode on that day.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/settings.py
new file mode 100644
index 000000000000..cf9b49923521
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/settings.py
@@ -0,0 +1,116 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+TRANSISTOR_BASE_URL = "https://api.transistor.fm/v1"
+
+# The docs give `pagination[per]` a default of 10 without stating a cap. 100 is what other
+# published Transistor integrations use; pagination terminates on the response's `meta`
+# block rather than on the page length, so a server-side clamp to a smaller page is handled.
+PAGE_SIZE = 100
+
+# Transistor allows 10 requests per 10 seconds and blocks for 10 seconds once exceeded, so
+# requests are paced just over one per second instead of relying on 429 backoff alone.
+MIN_REQUEST_INTERVAL_SECONDS = 1.1
+
+# Fan-out endpoints issue at least one request per show on every sync, so the parent list is
+# capped to bound a sync's outbound request count.
+MAX_SHOWS = 500
+
+# The analytics endpoints take an arbitrary start/end date range and answer in one response
+# (no pagination), but the docs don't state a maximum range. Requests are windowed so a long
+# backfill is split into predictable chunks that also act as resume checkpoints.
+ANALYTICS_WINDOW_DAYS = 365
+
+# How far back a first (non-incremental) analytics sync reaches when a show's creation date
+# can't be read from the show row.
+ANALYTICS_MAX_BACKFILL_DAYS = 5 * 365
+
+# Podcast downloads for a given day keep accruing for weeks as listeners catch up, so
+# incremental analytics syncs re-read a trailing window instead of freezing each day at its
+# first-imported value.
+ANALYTICS_LOOKBACK_SECONDS = 14 * 24 * 60 * 60
+
+_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [incremental_field("date", IncrementalFieldType.Date)]
+
+
+@dataclass
+class TransistorEndpointConfig:
+ name: str
+ primary_keys: list[str]
+ # `True` only for the analytics endpoints, which take a server-side `start_date`/`end_date`
+ # window. The entity list endpoints have no updated-since filter, so they are full refresh.
+ supports_incremental: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable date/datetime column used for partitioning; never a mutable timestamp.
+ partition_key: Optional[str] = None
+ default_incremental_lookback_seconds: Optional[int] = None
+ description: Optional[str] = None
+
+
+TRANSISTOR_ENDPOINTS: dict[str, TransistorEndpointConfig] = {
+ "shows": TransistorEndpointConfig(
+ name="shows",
+ primary_keys=["id"],
+ description="Podcasts on the account, one row per show, with title, description, "
+ "category, feed URL, and privacy settings.",
+ ),
+ "episodes": TransistorEndpointConfig(
+ name="episodes",
+ # Episode ids are account-wide identifiers, so the show id is carried as a column but
+ # is not needed to make the key unique.
+ primary_keys=["id"],
+ partition_key="created_at",
+ description="Episodes across every show on the account, including drafts and scheduled "
+ "episodes, with audio, artwork, and publishing metadata.",
+ ),
+ "subscribers": TransistorEndpointConfig(
+ name="subscribers",
+ # Fetched per show, so the show id is part of the key even though subscriber ids look
+ # account-wide — the docs don't promise global uniqueness.
+ primary_keys=["show_id", "id"],
+ partition_key="created_at",
+ description="Private podcast subscribers, one row per subscriber per show. Only shows "
+ "marked private have subscribers.",
+ ),
+ "webhooks": TransistorEndpointConfig(
+ name="webhooks",
+ primary_keys=["show_id", "id"],
+ description="Webhook subscriptions registered on each show, with the subscribed event name and delivery URL.",
+ ),
+ "show_analytics": TransistorEndpointConfig(
+ name="show_analytics",
+ primary_keys=["show_id", "date"],
+ supports_incremental=True,
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ # A day's download count never moves to another day, so `date` is a stable partition key.
+ partition_key="date",
+ default_incremental_lookback_seconds=ANALYTICS_LOOKBACK_SECONDS,
+ description="Daily download counts per show, one row per show per day.",
+ ),
+ "episode_analytics": TransistorEndpointConfig(
+ name="episode_analytics",
+ primary_keys=["show_id", "episode_id", "date"],
+ supports_incremental=True,
+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),
+ partition_key="date",
+ default_incremental_lookback_seconds=ANALYTICS_LOOKBACK_SECONDS,
+ description="Daily download counts per episode, one row per episode per day.",
+ ),
+}
+
+ENDPOINTS = tuple(TRANSISTOR_ENDPOINTS.keys())
+
+# Endpoints fetched once per show. `shows` is the parent list itself.
+FANOUT_ENDPOINTS = tuple(name for name in ENDPOINTS if name != "shows")
+
+# Endpoints that walk pages of a JSON:API list rather than a date-windowed analytics document.
+PAGINATED_ENDPOINTS = ("shows", "episodes", "subscribers", "webhooks")
+
+ANALYTICS_ENDPOINTS = ("show_analytics", "episode_analytics")
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TRANSISTOR_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/source.py
index 4e888cd67341..a04c2cb0f7d4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/source.py
@@ -1,21 +1,45 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.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
+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.transistor import (
TransistorSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ TRANSISTOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.transistor import (
+ TransistorResumeConfig,
+ transistor_source,
+ validate_credentials as validate_transistor_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TransistorSource(SimpleSource[TransistorSourceConfig]):
+class TransistorSource(ResumableSource[TransistorSourceConfig, TransistorResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # `/v1` is the only path Transistor has ever published and is not a documented version
+ # choice, so the source stays on the framework's unversioned default.
+ api_docs_url = "https://developers.transistor.fm/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TRANSISTOR
@@ -26,7 +50,96 @@ class TransistorSource(SimpleSource[TransistorSourceConfig]):
name=SchemaExternalDataSourceType.TRANSISTOR,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Transistor.fm",
+ keywords=["podcast", "transistor fm"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Sync your shows, episodes, private podcast subscribers, and daily download analytics from [Transistor](https://transistor.fm) into the PostHog Data warehouse.
+
+Create an API key in your Transistor account settings, then paste it below. The key has access to every show your Transistor user can see.
+
+Download analytics sync incrementally by day. The other tables sync as a full refresh.""",
iconPath="/static/services/transistor.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/transistor",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Transistor rejected the API key. Generate a new key in your Transistor account settings and reconnect.",
+ "403 Client Error: Forbidden for url": "This Transistor API key does not have access to the requested show. Check the key's account permissions and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TransistorSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=TRANSISTOR_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=TRANSISTOR_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=TRANSISTOR_ENDPOINTS[endpoint].description,
+ default_incremental_lookback_seconds=TRANSISTOR_ENDPOINTS[
+ endpoint
+ ].default_incremental_lookback_seconds,
+ detected_primary_keys=list(TRANSISTOR_ENDPOINTS[endpoint].primary_keys),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [schema for schema in schemas if schema.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: TransistorSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_transistor_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TransistorResumeConfig]:
+ return ResumableSourceManager[TransistorResumeConfig](inputs, TransistorResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TransistorSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TransistorResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return transistor_source(
+ endpoint=inputs.schema_name,
+ api_key=config.api_key,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py
new file mode 100644
index 000000000000..d56c7a5d8371
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor.py
@@ -0,0 +1,475 @@
+from datetime import date
+from typing import Any, Optional
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.settings import (
+ TRANSISTOR_BASE_URL,
+ TRANSISTOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.transistor import (
+ RequestThrottle,
+ TransistorResumeConfig,
+ date_windows,
+ episode_analytics_rows,
+ flatten_resource,
+ get_rows,
+ list_shows,
+ paginate,
+ parse_download_date,
+ show_analytics_rows,
+ transistor_source,
+ validate_credentials,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.transistor.transistor"
+
+LOGGER = structlog.get_logger()
+
+
+def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status
+ response.ok = 200 <= status < 300
+ response.json.return_value = body if body is not None else {}
+ if not response.ok:
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error for url: {TRANSISTOR_BASE_URL}", response=requests.Response()
+ )
+ return response
+
+
+class _FakeSession(requests.Session):
+ def __init__(self, responder) -> None:
+ super().__init__()
+ self._responder = responder
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def get(self, url: Any, **kwargs: Any) -> Any:
+ recorded = dict(kwargs.get("params") or {})
+ self.calls.append((str(url), recorded))
+ return self._responder(str(url), recorded)
+
+
+class _FakeResumableManager(ResumableSourceManager[TransistorResumeConfig]):
+ def __init__(self, state: TransistorResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TransistorResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TransistorResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TransistorResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _resource(resource_id: str, resource_type: str, attributes: dict[str, Any]) -> dict[str, Any]:
+ return {"id": resource_id, "type": resource_type, "attributes": attributes, "relationships": {}}
+
+
+def _list_body(items: list[dict[str, Any]], current_page: int = 1, total_pages: int = 1) -> dict[str, Any]:
+ return {"data": items, "meta": {"currentPage": current_page, "totalPages": total_pages, "totalCount": len(items)}}
+
+
+def _shows_body() -> dict[str, Any]:
+ return _list_body(
+ [
+ _resource("22", "show", {"title": "Second", "created_at": "2026-07-01T00:00:00Z"}),
+ _resource("11", "show", {"title": "First", "created_at": "2026-07-01T00:00:00Z"}),
+ ]
+ )
+
+
+def _run(responder, endpoint: str, manager: _FakeResumableManager, **kwargs) -> tuple[list[list[dict]], _FakeSession]:
+ session = _FakeSession(responder)
+ with mock.patch(f"{MODULE}._make_session", return_value=session):
+ batches = list(
+ get_rows(
+ endpoint=endpoint,
+ api_key="key",
+ logger=LOGGER,
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+ return batches, session
+
+
[email protected](autouse=True)
+def _no_throttle(monkeypatch):
+ monkeypatch.setattr(f"{MODULE}.MIN_REQUEST_INTERVAL_SECONDS", 0)
+
+
+class TestTransistorTransport:
+ def test_flatten_resource_hoists_attributes_and_relationships(self):
+ row = flatten_resource(
+ {
+ "id": "3056098",
+ "type": "episode",
+ "attributes": {"title": "How To Roast Coffee", "id": "attribute-id-should-lose"},
+ "relationships": {
+ "show": {"data": {"id": "132543", "type": "show"}},
+ "playlists": {"data": [{"id": "1"}, {"id": "2"}]},
+ "broken": "not-a-dict",
+ },
+ }
+ )
+
+ # Attributes land at the row root so columns are queryable without unnesting, and the
+ # JSON:API envelope id wins over any same-named attribute.
+ assert row["title"] == "How To Roast Coffee"
+ assert row["id"] == "3056098"
+ assert row["type"] == "episode"
+ assert row["show_id"] == "132543"
+ assert row["playlists_ids"] == ["1", "2"]
+ assert "broken" not in row
+
+ def test_flatten_resource_tolerates_missing_sections(self):
+ assert flatten_resource({"id": "1", "type": "show"}) == {"id": "1", "type": "show"}
+
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ # The documented parameter format is dd-mm-yyyy and wins when ambiguous.
+ ("18-07-2026", date(2026, 7, 18)),
+ ("07-08-2026", date(2026, 8, 7)),
+ # Response samples are inconsistent, so ISO and mm-dd-yyyy are accepted as fallbacks.
+ ("2026-07-18", date(2026, 7, 18)),
+ ("07-18-2026", date(2026, 7, 18)),
+ (" 18-07-2026 ", date(2026, 7, 18)),
+ ("not-a-date", None),
+ ("", None),
+ (None, None),
+ (20260718, None),
+ ],
+ )
+ def test_parse_download_date(self, raw, expected):
+ assert parse_download_date(raw) == expected
+
+ @pytest.mark.parametrize(
+ "start, end, window_days, expected",
+ [
+ (date(2026, 1, 1), date(2026, 1, 1), 5, [(date(2026, 1, 1), date(2026, 1, 1))]),
+ (date(2026, 1, 1), date(2026, 1, 5), 5, [(date(2026, 1, 1), date(2026, 1, 5))]),
+ (
+ date(2026, 1, 1),
+ date(2026, 1, 7),
+ 5,
+ [(date(2026, 1, 1), date(2026, 1, 5)), (date(2026, 1, 6), date(2026, 1, 7))],
+ ),
+ # An end before the start yields nothing rather than looping.
+ (date(2026, 1, 5), date(2026, 1, 1), 5, []),
+ ],
+ )
+ def test_date_windows_are_contiguous_and_bounded(self, start, end, window_days, expected):
+ assert list(date_windows(start, end, window_days)) == expected
+
+ def test_paginate_follows_meta_and_stops_at_the_last_page(self):
+ pages = {
+ 1: _list_body([_resource("1", "show", {})], current_page=1, total_pages=3),
+ 2: _list_body([_resource("2", "show", {})], current_page=2, total_pages=3),
+ 3: _list_body([_resource("3", "show", {})], current_page=3, total_pages=3),
+ }
+
+ def responder(url, params):
+ return _response(200, pages[params.get("pagination[page]", 1)])
+
+ session = _FakeSession(responder)
+ results = list(paginate(session, RequestThrottle(0), f"{TRANSISTOR_BASE_URL}/shows", {}, LOGGER))
+
+ assert [next_page for _, next_page in results] == [2, 3, None]
+ # The first request omits the page param so the API's own base page applies, and later
+ # pages come from `currentPage` rather than an assumed base.
+ assert "pagination[page]" not in session.calls[0][1]
+ assert [call[1].get("pagination[page]") for call in session.calls] == [None, 2, 3]
+ assert all(call[1]["pagination[per]"] for call in session.calls)
+
+ def test_paginate_seeds_the_resumed_page(self):
+ session = _FakeSession(lambda url, params: _response(200, _list_body([], current_page=4, total_pages=4)))
+
+ list(paginate(session, RequestThrottle(0), f"{TRANSISTOR_BASE_URL}/shows", {}, LOGGER, start_page=4))
+
+ assert session.calls[0][1]["pagination[page]"] == 4
+
+ @pytest.mark.parametrize("row_count, expected_next", [(100, 2), (3, None)])
+ def test_paginate_without_meta_walks_only_while_pages_are_full(self, row_count, expected_next):
+ body = {"data": [_resource(str(index), "webhook", {}) for index in range(row_count)]}
+ session = _FakeSession(lambda url, params: _response(200, body))
+
+ rows, next_page = next(paginate(session, RequestThrottle(0), f"{TRANSISTOR_BASE_URL}/webhooks", {}, LOGGER))
+
+ assert len(rows) == row_count
+ assert next_page == expected_next
+
+ def test_paginate_skips_a_404_instead_of_failing(self):
+ session = _FakeSession(lambda url, params: _response(404))
+
+ results = list(paginate(session, RequestThrottle(0), f"{TRANSISTOR_BASE_URL}/subscribers", {}, LOGGER))
+
+ assert results == [([], None)]
+
+ def test_list_shows_is_sorted_by_id(self):
+ session = _FakeSession(lambda url, params: _response(200, _shows_body()))
+
+ shows = list_shows(session, RequestThrottle(0), LOGGER)
+
+ # Sorted by id, so fan-out resume indexes stay stable even though the endpoint orders
+ # by updated date, which reshuffles whenever a show is edited.
+ assert [show["id"] for show in shows] == ["11", "22"]
+
+ def test_list_shows_is_capped(self, monkeypatch):
+ monkeypatch.setattr(f"{MODULE}.MAX_SHOWS", 1)
+ session = _FakeSession(lambda url, params: _response(200, _shows_body()))
+
+ assert len(list_shows(session, RequestThrottle(0), LOGGER)) == 1
+
+ def test_shows_yields_rows_and_checkpoints_each_page(self):
+ pages = {
+ 1: _list_body([_resource("11", "show", {"title": "First"})], current_page=1, total_pages=2),
+ 2: _list_body([_resource("22", "show", {"title": "Second"})], current_page=2, total_pages=2),
+ }
+ manager = _FakeResumableManager()
+
+ batches, _ = _run(
+ lambda url, params: _response(200, pages[params.get("pagination[page]", 1)]), "shows", manager
+ )
+
+ assert [row["title"] for batch in batches for row in batch] == ["First", "Second"]
+ # State is only saved while there is a next page to resume to.
+ assert [state.page for state in manager.saved] == [2]
+
+ def test_fanout_rows_carry_the_show_id_and_advance_the_checkpoint(self):
+ def responder(url, params):
+ if url.endswith("/shows"):
+ return _response(200, _shows_body())
+ return _response(200, _list_body([_resource("709423", "subscriber", {"email": "[email protected]"})]))
+
+ manager = _FakeResumableManager()
+ batches, _ = _run(responder, "subscribers", manager)
+
+ rows = [row for batch in batches for row in batch]
+ # `show_id` completes the [show_id, id] primary key for a stream fetched per show.
+ assert [(row["show_id"], row["id"]) for row in rows] == [("11", "709423"), ("22", "709423")]
+ assert [(state.show_index, state.page) for state in manager.saved] == [(1, None), (2, None)]
+
+ def test_fanout_resumes_at_the_saved_show_and_page(self):
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def responder(url, params):
+ calls.append((url, params))
+ if url.endswith("/shows"):
+ return _response(200, _shows_body())
+ return _response(200, _list_body([_resource("1", "episode", {"title": "One"})]))
+
+ manager = _FakeResumableManager(TransistorResumeConfig(show_index=1, page=3))
+ batches, _ = _run(responder, "episodes", manager)
+
+ episode_calls = [params for url, params in calls if url.endswith("/episodes")]
+ # Only the second show is fetched, and it restarts on the saved page instead of page one.
+ assert len(episode_calls) == 1
+ assert episode_calls[0]["show_id"] == "22"
+ assert episode_calls[0]["pagination[page]"] == 3
+ # `order=asc` pins the walk so mid-sync publishes don't shift later pages.
+ assert episode_calls[0]["order"] == "asc"
+ assert [row["show_id"] for batch in batches for row in batch] == ["22"]
+
+ @freeze_time("2026-08-04")
+ @pytest.mark.parametrize(
+ "should_use_incremental_field, last_value, expected_start",
+ [
+ # A first sync reaches back to the show's creation date.
+ (False, None, "01-07-2026"),
+ # An incremental sync starts at the watermark the pipeline hands over.
+ (True, "2026-08-01", "01-08-2026"),
+ (True, None, "01-07-2026"),
+ ],
+ )
+ def test_show_analytics_window_start(self, should_use_incremental_field, last_value, expected_start):
+ analytics_params: list[dict[str, Any]] = []
+
+ def responder(url, params):
+ if url.endswith("/shows"):
+ return _response(200, _list_body([_resource("11", "show", {"created_at": "2026-07-01T00:00:00Z"})]))
+ analytics_params.append(params)
+ return _response(200, {"data": {"attributes": {"downloads": [{"date": "18-07-2026", "downloads": 7}]}}})
+
+ batches, _ = _run(
+ responder,
+ "show_analytics",
+ _FakeResumableManager(),
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+
+ assert analytics_params == [{"start_date": expected_start, "end_date": "04-08-2026"}]
+ assert batches == [
+ [{"show_id": "11", "date": "2026-07-18", "raw_date": "18-07-2026", "downloads": 7}],
+ ]
+
+ @freeze_time("2026-08-04")
+ def test_analytics_splits_long_backfills_into_windows_and_checkpoints_each(self):
+ analytics_params: list[dict[str, Any]] = []
+
+ def responder(url, params):
+ if url.endswith("/shows"):
+ return _response(200, _list_body([_resource("11", "show", {"created_at": "2024-01-01T00:00:00Z"})]))
+ analytics_params.append(params)
+ return _response(200, {"data": {"attributes": {"downloads": []}}})
+
+ manager = _FakeResumableManager()
+ _run(responder, "show_analytics", manager, should_use_incremental_field=False)
+
+ assert [params["start_date"] for params in analytics_params] == ["01-01-2024", "31-12-2024", "31-12-2025"]
+ # Each finished window is a resume point; the final one advances past the show.
+ assert [(state.show_index, state.window_start) for state in manager.saved] == [
+ (0, "2024-12-31"),
+ (0, "2025-12-31"),
+ (1, None),
+ ]
+
+ @freeze_time("2026-08-04")
+ def test_analytics_resumes_at_the_saved_window(self):
+ analytics_params: list[dict[str, Any]] = []
+
+ def responder(url, params):
+ if url.endswith("/shows"):
+ return _response(200, _list_body([_resource("11", "show", {"created_at": "2024-01-01T00:00:00Z"})]))
+ analytics_params.append(params)
+ return _response(200, {"data": {"attributes": {"downloads": []}}})
+
+ manager = _FakeResumableManager(TransistorResumeConfig(show_index=0, window_start="2025-12-31"))
+ _run(responder, "show_analytics", manager, should_use_incremental_field=False)
+
+ assert [params["start_date"] for params in analytics_params] == ["31-12-2025"]
+
+ def test_show_analytics_rows_drop_unparseable_dates(self):
+ payload = {
+ "data": {
+ "attributes": {
+ "downloads": [
+ {"date": "18-07-2026", "downloads": 3},
+ {"date": "whenever", "downloads": 4},
+ "not-a-dict",
+ ]
+ }
+ }
+ }
+
+ rows = list(show_analytics_rows("11", payload))
+
+ assert rows == [{"show_id": "11", "date": "2026-07-18", "raw_date": "18-07-2026", "downloads": 3}]
+
+ def test_episode_analytics_rows_carry_the_full_primary_key(self):
+ payload = {
+ "data": {
+ "attributes": {
+ "episodes": [
+ {
+ "id": 2,
+ "title": "Episode Two",
+ "published_at": "2026-07-23 04:57:15 UTC",
+ "downloads": [{"date": "18-07-2026", "downloads": 9}],
+ },
+ {"title": "no id, skipped", "downloads": [{"date": "18-07-2026", "downloads": 1}]},
+ ]
+ }
+ }
+ }
+
+ rows = list(episode_analytics_rows("11", payload))
+
+ assert rows == [
+ {
+ "show_id": "11",
+ "episode_id": "2",
+ "episode_title": "Episode Two",
+ "episode_published_at": "2026-07-23 04:57:15 UTC",
+ "date": "2026-07-18",
+ "raw_date": "18-07-2026",
+ "downloads": 9,
+ }
+ ]
+
+ @pytest.mark.parametrize("endpoint", list(TRANSISTOR_ENDPOINTS))
+ def test_source_response_shape_per_endpoint(self, endpoint):
+ config = TRANSISTOR_ENDPOINTS[endpoint]
+
+ response = transistor_source(
+ endpoint=endpoint,
+ api_key="key",
+ logger=LOGGER,
+ resumable_source_manager=_FakeResumableManager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Fan-out restarts dates at every show, so the watermark must only commit at completion.
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == ([config.partition_key] if config.partition_key else None)
+
+ @pytest.mark.parametrize(
+ "status, expected_ok, expected_message_fragment",
+ [
+ (200, True, None),
+ (401, False, "rejected the API key"),
+ (403, False, "rejected the API key"),
+ (500, False, "unexpected status code: 500"),
+ ],
+ )
+ def test_validate_credentials_status_mapping(self, status, expected_ok, expected_message_fragment):
+ session = _FakeSession(lambda url, params: _response(status))
+
+ with mock.patch(f"{MODULE}._make_session", return_value=session):
+ ok, message = validate_credentials("key")
+
+ assert ok is expected_ok
+ if expected_message_fragment is None:
+ assert message is None
+ else:
+ assert expected_message_fragment in (message or "")
+
+ @pytest.mark.parametrize("api_key", ["", " ", None])
+ def test_validate_credentials_rejects_a_blank_key_without_a_request(self, api_key):
+ with mock.patch(f"{MODULE}._make_session") as make_session:
+ ok, message = validate_credentials(api_key)
+
+ assert ok is False
+ assert message == "An API key is required."
+ make_session.assert_not_called()
+
+ def test_validate_credentials_reports_an_unreachable_api(self):
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+
+ with mock.patch(f"{MODULE}._make_session", return_value=session):
+ ok, message = validate_credentials("key")
+
+ assert ok is False
+ assert message is not None and "Could not reach" in message
+
+
+class TestRequestThrottle:
+ def test_paces_requests_to_the_minimum_interval(self):
+ # Transistor blocks for 10 seconds once 10 requests land in 10 seconds, so requests are
+ # paced rather than left to 429 backoff.
+ clock = iter([0.0, 0.5, 1.1])
+ sleeps: list[float] = []
+
+ with (
+ mock.patch("time.monotonic", lambda: next(clock)),
+ mock.patch("time.sleep", lambda seconds: sleeps.append(seconds)),
+ ):
+ throttle = RequestThrottle(1.0)
+ throttle.wait()
+ throttle.wait()
+
+ assert sleeps == [0.5]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor_source.py
new file mode 100644
index 000000000000..a7fa5af9b195
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/tests/test_transistor_source.py
@@ -0,0 +1,182 @@
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.transistor import (
+ TransistorSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.settings import (
+ ENDPOINTS,
+ TRANSISTOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.source import TransistorSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.transistor import (
+ TransistorResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.transistor.source"
+
+
+def _make_inputs(
+ schema_name: str = "shows",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="date" if should_use_incremental_field else None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestTransistorSource:
+ def setup_method(self):
+ self.source = TransistorSource()
+ self.config = TransistorSourceConfig(api_key="secret-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.TRANSISTOR
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Transistor"
+ assert config.label == "Transistor.fm"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source must be visible in the wizard, not hidden behind unreleasedSource.
+ assert not config.unreleasedSource
+
+ def test_api_key_field_is_stored_as_a_secret(self):
+ fields = [field for field in self.source.get_source_config.fields if isinstance(field, SourceFieldInputConfig)]
+
+ assert [field.name for field in fields] == ["api_key"]
+ # A non-password, non-secret field would leak the key into non-sensitive job inputs.
+ assert fields[0].type == SourceFieldInputConfigType.PASSWORD
+ assert fields[0].secret is True
+ assert fields[0].required is True
+
+ def test_get_schemas_matches_the_endpoint_catalog(self):
+ schemas = self.source.get_schemas(self.config, team_id=123)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ for schema in schemas:
+ endpoint = TRANSISTOR_ENDPOINTS[schema.name]
+ assert schema.detected_primary_keys == endpoint.primary_keys
+ assert schema.supports_incremental is endpoint.supports_incremental
+
+ @pytest.mark.parametrize(
+ "endpoint, supports_incremental",
+ [
+ # Only the analytics endpoints take a server-side start_date/end_date filter; the
+ # entity lists have no updated-since filter, so advertising incremental would make
+ # every sync silently re-read everything.
+ ("shows", False),
+ ("episodes", False),
+ ("subscribers", False),
+ ("webhooks", False),
+ ("show_analytics", True),
+ ("episode_analytics", True),
+ ],
+ )
+ def test_incremental_support_per_endpoint(self, endpoint, supports_incremental):
+ schema = self.source.get_schemas(self.config, team_id=123, names=[endpoint])[0]
+
+ assert schema.supports_incremental is supports_incremental
+ assert [field["field"] for field in schema.incremental_fields] == (["date"] if supports_incremental else [])
+ # Download counts keep accruing for days, so incremental analytics re-read a trailing window.
+ assert (schema.default_incremental_lookback_seconds is not None) is supports_incremental
+
+ def test_get_schemas_filters_by_name(self):
+ schemas = self.source.get_schemas(self.config, team_id=123, names=["show_analytics", "unknown"])
+
+ assert [schema.name for schema in schemas] == ["show_analytics"]
+
+ def test_documented_tables_render_without_credentials(self):
+ # Public source docs call get_schemas with a placeholder config; a source that made a
+ # request here would hang the docs endpoint.
+ tables = self.source.get_documented_tables()
+
+ assert [table["name"] for table in tables] == list(ENDPOINTS)
+ assert all(table["description"] for table in tables)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert set(descriptions) == set(ENDPOINTS)
+ for endpoint, entry in descriptions.items():
+ # Every primary key column needs a description, since those are the join keys the
+ # agent reasons about.
+ assert set(TRANSISTOR_ENDPOINTS[endpoint].primary_keys) <= set(entry.get("columns", {}))
+
+ @pytest.mark.parametrize(
+ "result",
+ [(True, None), (False, "Transistor rejected the API key.")],
+ )
+ def test_validate_credentials_delegates_to_the_transport(self, result):
+ with mock.patch(f"{SOURCE_MODULE}.validate_transistor_credentials", return_value=result) as validate:
+ assert self.source.validate_credentials(self.config, team_id=123) == result
+
+ validate.assert_called_once_with("secret-key")
+
+ @pytest.mark.parametrize("status", ["401", "403"])
+ def test_auth_failures_are_non_retryable(self, status):
+ errors = self.source.get_non_retryable_errors()
+
+ # Without these the job retries a permanently bad key until the schedule gives up.
+ assert any(status in pattern for pattern in errors)
+ assert all(message for message in errors.values())
+
+ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self):
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TransistorResumeConfig
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_source_for_pipeline_uses_the_endpoint_primary_keys(self, endpoint):
+ manager = self.source.get_resumable_source_manager(_make_inputs(schema_name=endpoint))
+
+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs(schema_name=endpoint))
+
+ assert response.name == endpoint
+ assert response.primary_keys == TRANSISTOR_ENDPOINTS[endpoint].primary_keys
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field, expected_last_value",
+ [(True, "2026-08-01"), (False, None)],
+ )
+ def test_source_for_pipeline_only_passes_the_watermark_when_syncing_incrementally(
+ self, should_use_incremental_field, expected_last_value
+ ):
+ inputs = _make_inputs(
+ schema_name="show_analytics",
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value="2026-08-01",
+ )
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ with mock.patch(f"{SOURCE_MODULE}.transistor_source") as transistor_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = cast(dict[str, Any], transistor_source.call_args.kwargs)
+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field
+ assert kwargs["db_incremental_field_last_value"] == expected_last_value
+ assert kwargs["api_key"] == "secret-key"
+ assert kwargs["endpoint"] == "show_analytics"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/transistor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/transistor.py
new file mode 100644
index 000000000000..d9b8d0b70210
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/transistor/transistor.py
@@ -0,0 +1,463 @@
+import time
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import quote
+
+import requests
+from dateutil import parser as date_parser
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (
+ DEFAULT_RETRY,
+ make_tracked_session,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.transistor.settings import (
+ ANALYTICS_MAX_BACKFILL_DAYS,
+ ANALYTICS_WINDOW_DAYS,
+ MAX_SHOWS,
+ MIN_REQUEST_INTERVAL_SECONDS,
+ PAGE_SIZE,
+ TRANSISTOR_BASE_URL,
+ TRANSISTOR_ENDPOINTS,
+ TransistorEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+# Rows are yielded in bounded chunks so a show with a long download history never forces one
+# oversized in-memory Arrow conversion downstream.
+MAX_ROWS_PER_BATCH = 5000
+
+# Transistor blocks for a full 10 seconds after a 429, which the transport's default backoff
+# (0.5s factor over 3 attempts) can't wait out. Everything else stays as the shared default.
+_TRANSISTOR_RETRY = DEFAULT_RETRY.new(total=5, backoff_factor=5)
+
+# The documented parameter format is dd-mm-yyyy. The published response samples are
+# inconsistent (some show mm-dd-yyyy), so download dates are parsed through an ordered ladder
+# and the untouched value is kept alongside as `raw_date`.
+_DOWNLOAD_DATE_FORMATS = ("%d-%m-%Y", "%Y-%m-%d", "%m-%d-%Y")
+
+
+class TransistorResumeConfig:
+ # Index into the show list (sorted by show id) of the next show still to fetch. Always 0
+ # for `shows`, which is the parent list itself.
+ show_index: int = 0
+ # Next page to request within the current show's list endpoint. `None` starts at the API's
+ # first page.
+ page: Optional[int] = None
+ # Analytics only: start of the next date window (ISO `YYYY-MM-DD`) for the current show.
+ window_start: Optional[str] = None
+
+
+class RequestThrottle:
+ """Paces outbound requests to stay under Transistor's 10 requests / 10 seconds limit."""
+
+ def __init__(self, min_interval_seconds: float) -> None:
+ self._min_interval = min_interval_seconds
+ self._last: float | None = None
+
+ def wait(self) -> None:
+ if self._last is not None:
+ remaining = self._min_interval - (time.monotonic() - self._last)
+ if remaining > 0:
+ time.sleep(remaining)
+ self._last = time.monotonic()
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # `redact_values` masks the key wherever the tracked transport logs it; `capture=False`
+ # because subscriber rows carry customer email addresses.
+ return make_tracked_session(
+ headers={"x-api-key": api_key, "Accept": "application/json"},
+ redact_values=(api_key,),
+ capture=False,
+ retry=_TRANSISTOR_RETRY,
+ )
+
+
+def flatten_resource(item: dict[str, Any]) -> dict[str, Any]:
+ """Flatten one JSON:API resource object into a warehouse row.
+
+ `attributes` are hoisted to the row root, the resource `id`/`type` are set from the
+ envelope (they win over any same-named attribute), and each relationship contributes a
+ `<name>_id` (or `<name>_ids`) column so joins don't need the nested document.
+ """
+ attributes = item.get("attributes")
+ row: dict[str, Any] = dict(attributes) if isinstance(attributes, dict) else {}
+ row["id"] = item.get("id")
+ row["type"] = item.get("type")
+
+ relationships = item.get("relationships")
+ if isinstance(relationships, dict):
+ for name, relationship in relationships.items():
+ if not isinstance(relationship, dict):
+ continue
+ data = relationship.get("data")
+ if isinstance(data, dict):
+ row[f"{name}_id"] = data.get("id")
+ elif isinstance(data, list):
+ row[f"{name}_ids"] = [entry.get("id") for entry in data if isinstance(entry, dict)]
+ return row
+
+
+def _fetch_json(
+ session: requests.Session,
+ throttle: RequestThrottle,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ throttle.wait()
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # A show can be deleted mid-sync, and subscriber/webhook lookups 404 for shows that don't
+ # have them; skipping the show beats failing the whole sync.
+ if response.status_code == 404:
+ logger.warning(f"Transistor: {url} returned 404, skipping")
+ return {}
+
+ response.raise_for_status()
+ payload = response.json()
+ return payload if isinstance(payload, dict) else {}
+
+
+def paginate(
+ session: requests.Session,
+ throttle: RequestThrottle,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+ start_page: int | None = None,
+) -> Iterator[tuple[list[dict[str, Any]], int | None]]:
+ """Walk a JSON:API list endpoint, yielding `(rows, next_page)` per page.
+
+ The first request omits `pagination[page]` so the API's own base page applies (the docs
+ say 0, responses report `currentPage` starting at 1), and every following page is derived
+ from the response's `meta` block rather than from an assumed base.
+ """
+ page = start_page
+
+ while True:
+ request_params = {**params, "pagination[per]": PAGE_SIZE}
+ if page is not None:
+ request_params["pagination[page]"] = page
+
+ payload = _fetch_json(session, throttle, url, request_params, logger)
+ items = payload.get("data")
+ rows = [flatten_resource(item) for item in items if isinstance(item, dict)] if isinstance(items, list) else []
+
+ meta = payload.get("meta")
+ current_page = meta.get("currentPage") if isinstance(meta, dict) else None
+ total_pages = meta.get("totalPages") if isinstance(meta, dict) else None
+
+ next_page: int | None = None
+ if isinstance(current_page, int) and isinstance(total_pages, int):
+ if current_page < total_pages:
+ next_page = current_page + 1
+ elif len(rows) >= PAGE_SIZE:
+ # No pagination metadata (the webhooks list has none): keep walking only while
+ # pages come back full.
+ next_page = (page or 1) + 1
+
+ yield rows, next_page
+
+ if next_page is None:
+ return
+ page = next_page
+
+
+def list_shows(
+ session: requests.Session, throttle: RequestThrottle, logger: FilteringBoundLogger
+) -> list[dict[str, Any]]:
+ """Every show on the account, ordered by show id.
+
+ The endpoint orders by updated date, which reshuffles whenever a show is edited. Fan-out
+ resume state is an index into this list, so it is re-sorted into a stable order first.
+ """
+ shows: list[dict[str, Any]] = []
+ for rows, _ in paginate(session, throttle, f"{TRANSISTOR_BASE_URL}/shows", {}, logger):
+ shows.extend(rows)
+ if len(shows) >= MAX_SHOWS:
+ logger.warning(f"Transistor: show list capped at {MAX_SHOWS}; later shows are not synced")
+ shows = shows[:MAX_SHOWS]
+ break
+ return sorted(shows, key=lambda show: str(show.get("id") or ""))
+
+
+def format_api_date(value: date) -> str:
+ """Format a date the way the analytics endpoints document their filters: dd-mm-yyyy."""
+ return value.strftime("%d-%m-%Y")
+
+
+def parse_download_date(raw: Any) -> date | None:
+ if not isinstance(raw, str):
+ return None
+ for date_format in _DOWNLOAD_DATE_FORMATS:
+ try:
+ return datetime.strptime(raw.strip(), date_format).date()
+ except ValueError:
+ continue
+ return None
+
+
+def _coerce_date(value: Any) -> date | None:
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ if isinstance(value, str):
+ try:
+ return date_parser.parse(value).date()
+ except (ValueError, OverflowError):
+ return None
+ return None
+
+
+def date_windows(start: date, end: date, window_days: int = ANALYTICS_WINDOW_DAYS) -> Iterator[tuple[date, date]]:
+ cursor = start
+ while cursor <= end:
+ window_end = min(cursor + timedelta(days=window_days - 1), end)
+ yield cursor, window_end
+ cursor = window_end + timedelta(days=1)
+
+
+def _analytics_start_date(
+ show: dict[str, Any],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ today: date,
+) -> date:
+ floor = today - timedelta(days=ANALYTICS_MAX_BACKFILL_DAYS)
+ if should_use_incremental_field:
+ watermark = _coerce_date(db_incremental_field_last_value)
+ if watermark is not None:
+ return max(watermark, floor)
+ # A first sync reaches back to the show's own creation date, which is both the earliest
+ # date that can have downloads and a natural bound on the backfill.
+ created_at = _coerce_date(show.get("created_at"))
+ return max(created_at, floor) if created_at is not None else floor
+
+
+def _download_rows(show_id: str, extra: dict[str, Any], downloads: Any) -> Iterator[dict[str, Any]]:
+ if not isinstance(downloads, list):
+ return
+ for entry in downloads:
+ if not isinstance(entry, dict):
+ continue
+ parsed = parse_download_date(entry.get("date"))
+ if parsed is None:
+ continue
+ yield {
+ "show_id": show_id,
+ **extra,
+ "date": parsed.isoformat(),
+ "raw_date": entry.get("date"),
+ "downloads": entry.get("downloads"),
+ }
+
+
+def show_analytics_rows(show_id: str, payload: dict[str, Any]) -> Iterator[dict[str, Any]]:
+ attributes = (payload.get("data") or {}).get("attributes") or {}
+ yield from _download_rows(show_id, {}, attributes.get("downloads"))
+
+
+def episode_analytics_rows(show_id: str, payload: dict[str, Any]) -> Iterator[dict[str, Any]]:
+ attributes = (payload.get("data") or {}).get("attributes") or {}
+ episodes = attributes.get("episodes")
+ if not isinstance(episodes, list):
+ return
+ for episode in episodes:
+ if not isinstance(episode, dict):
+ continue
+ episode_id = episode.get("id")
+ if episode_id is None:
+ continue
+ extra = {
+ "episode_id": str(episode_id),
+ "episode_title": episode.get("title"),
+ "episode_published_at": episode.get("published_at"),
+ }
+ yield from _download_rows(show_id, extra, episode.get("downloads"))
+
+
+def _chunked(rows: Iterator[dict[str, Any]]) -> Iterator[list[dict[str, Any]]]:
+ chunk: list[dict[str, Any]] = []
+ for row in rows:
+ chunk.append(row)
+ if len(chunk) >= MAX_ROWS_PER_BATCH:
+ yield chunk
+ chunk = []
+ if chunk:
+ yield chunk
+
+
+def _list_request(endpoint: str, show_id: str) -> tuple[str, dict[str, Any]]:
+ if endpoint == "episodes":
+ # `order=asc` pins the walk to oldest-first by published date so a new episode
+ # published mid-sync is appended rather than shifting every later page.
+ return f"{TRANSISTOR_BASE_URL}/episodes", {"show_id": show_id, "order": "asc"}
+ if endpoint == "subscribers":
+ return f"{TRANSISTOR_BASE_URL}/subscribers", {"show_id": show_id}
+ return f"{TRANSISTOR_BASE_URL}/webhooks", {"show_id": show_id}
+
+
+def _analytics_request(endpoint: str, show_id: str, window_start: date, window_end: date) -> tuple[str, dict[str, Any]]:
+ safe_show_id = quote(show_id, safe="")
+ path = (
+ f"{TRANSISTOR_BASE_URL}/analytics/{safe_show_id}"
+ if endpoint == "show_analytics"
+ else f"{TRANSISTOR_BASE_URL}/analytics/{safe_show_id}/episodes"
+ )
+ return path, {"start_date": format_api_date(window_start), "end_date": format_api_date(window_end)}
+
+
+def get_rows(
+ endpoint: str,
+ api_key: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TransistorResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ # One session reused across every request so urllib3 keeps the connection alive.
+ session = _make_session(api_key)
+ throttle = RequestThrottle(MIN_REQUEST_INTERVAL_SECONDS)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if endpoint == "shows":
+ start_page = resume.page if resume is not None else None
+ if start_page is not None:
+ logger.debug(f"Transistor: resuming shows from page {start_page}")
+ for rows, next_page in paginate(session, throttle, f"{TRANSISTOR_BASE_URL}/shows", {}, logger, start_page):
+ if rows:
+ yield rows
+ # Saved after yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes on the primary key.
+ if next_page is not None:
+ resumable_source_manager.save_state(TransistorResumeConfig(page=next_page))
+ return
+
+ shows = list_shows(session, throttle, logger)
+ start_index = resume.show_index if resume is not None else 0
+ if start_index:
+ logger.debug(f"Transistor: resuming {endpoint} from show index {start_index}")
+
+ today = datetime.now(UTC).date()
+
+ for index in range(start_index, len(shows)):
+ show = shows[index]
+ show_id = show.get("id")
+ if show_id is None:
+ continue
+ show_id = str(show_id)
+ # Resume hints only apply to the show the previous attempt stopped on.
+ resume_for_show = resume if resume is not None and index == start_index else None
+
+ if endpoint in ("show_analytics", "episode_analytics"):
+ window_start = _coerce_date(resume_for_show.window_start) if resume_for_show is not None else None
+ if window_start is None:
+ window_start = _analytics_start_date(
+ show, should_use_incremental_field, db_incremental_field_last_value, today
+ )
+
+ windows = list(date_windows(window_start, today))
+ if not windows:
+ # Nothing left for this show (a watermark already at or past today), so move the
+ # checkpoint on rather than leaving a resume stuck here.
+ resumable_source_manager.save_state(TransistorResumeConfig(show_index=index + 1))
+ continue
+
+ for start, end in windows:
+ url, params = _analytics_request(endpoint, show_id, start, end)
+ payload = _fetch_json(session, throttle, url, params, logger)
+ analytics_rows = (
+ show_analytics_rows(show_id, payload)
+ if endpoint == "show_analytics"
+ else episode_analytics_rows(show_id, payload)
+ )
+ yield from _chunked(analytics_rows)
+
+ next_window_start = end + timedelta(days=1)
+ if next_window_start <= today:
+ resumable_source_manager.save_state(
+ TransistorResumeConfig(show_index=index, window_start=next_window_start.isoformat())
+ )
+ else:
+ resumable_source_manager.save_state(TransistorResumeConfig(show_index=index + 1))
+ continue
+
+ url, params = _list_request(endpoint, show_id)
+ start_page = resume_for_show.page if resume_for_show is not None else None
+ for rows, next_page in paginate(session, throttle, url, params, logger, start_page):
+ if rows:
+ yield [{**row, "show_id": show_id} for row in rows]
+ if next_page is not None:
+ resumable_source_manager.save_state(TransistorResumeConfig(show_index=index, page=next_page))
+ else:
+ resumable_source_manager.save_state(TransistorResumeConfig(show_index=index + 1))
+
+
+def transistor_source(
+ endpoint: str,
+ api_key: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TransistorResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config: TransistorEndpointConfig = TRANSISTOR_ENDPOINTS[endpoint]
+
+ partition_kwargs: dict[str, Any] = {}
+ if config.partition_key is not None:
+ partition_kwargs = {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [config.partition_key],
+ }
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ endpoint=endpoint,
+ api_key=api_key,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # Every stream but `shows` is fetched show by show, so dates restart at each show and
+ # the stream as a whole is not ascending. "desc" holds the incremental watermark back
+ # until the sync completes, which is the safe reading for a non-monotonic stream;
+ # mid-run progress is protected by the resumable state instead.
+ sort_mode="desc",
+ **partition_kwargs,
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ """One cheap probe of the account root, which returns the authenticated user."""
+ if not api_key or not api_key.strip():
+ return False, "An API key is required."
+
+ session = _make_session(api_key)
+ try:
+ response = session.get(TRANSISTOR_BASE_URL, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the Transistor API. Please try again."
+
+ if response.ok:
+ return True, None
+
+ if response.status_code in (401, 403):
+ return False, (
+ "Transistor rejected the API key. Generate a key under your Transistor account settings and reconnect."
+ )
+ return False, f"Transistor API returned an unexpected status code: {response.status_code}"