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): implement rss import source (#69361)

Tom Owersba3ac3c31be2
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 9d5d78319e51..80dbba109959 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -316,6 +316,7 @@ the row lists both.
| rocketlane | HTTP | requests | ✅ |
| rollbar | HTTP | requests | ✅ |
| rootly | HTTP | requests | ✅ |
+| rss | HTTP | requests | ✅ |
| ruddr | HTTP | requests | ✅ |
| safetyculture | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -682,7 +683,6 @@ doesn't conflict with concurrent PRs.
- rki_covid
- rocket_chat
- rocketlane
-- rss
- sage_hr
- sage_intacct
- sailthru
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 1751839bab0a..d779ff7a6ce2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2946,7 +2946,7 @@ class RootlySourceConfig(config.Config):
@config.config
class RssSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/canonical_descriptions.py
new file mode 100644
index 000000000000..facf14d3f57c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/canonical_descriptions.py
@@ -0,0 +1,69 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the RSS.com Core API v4 OpenAPI spec (https://api.rss.com/v4/docs).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "podcasts": {
+ "description": "A podcast hosted on your RSS.com account.",
+ "docs_url": "https://api.rss.com/v4/docs",
+ "columns": {
+ "id": "The unique ID of the podcast.",
+ "slug": "The URL slug of the podcast.",
+ "title": "The title of the podcast.",
+ "language": "The ISO 639-1 language code of the podcast.",
+ "role": "Your role on the podcast (e.g. owner or collaborator).",
+ "hibernated": "Whether the podcast is hibernated (paused hosting).",
+ "cover_url": "Public URL of the podcast cover image, if any.",
+ "redirect_url": "The URL the podcast's RSS feed redirects to, if any.",
+ "timestamp_created": "When the podcast was created.",
+ "timestamp_updated": "When the podcast was last updated.",
+ },
+ },
+ "episodes": {
+ "description": "An episode of a podcast hosted on your RSS.com account.",
+ "docs_url": "https://api.rss.com/v4/docs",
+ "columns": {
+ "id": "The unique ID of the episode within its podcast.",
+ "podcast_id": "The ID of the podcast the episode belongs to.",
+ "title": "The title of the episode.",
+ "description": "The description of the episode, also known as episode notes.",
+ "status": "The publishing status of the episode: draft, scheduled, or published.",
+ "duration": "The episode duration in seconds.",
+ "publish_datetime": "The publication date and time of the episode.",
+ "schedule_datetime": "When the episode is scheduled for publishing, if scheduled.",
+ "itunes_explicit": "Whether the episode includes explicit content. Null when unset.",
+ "itunes_episode": "The Apple Podcasts episode number.",
+ "itunes_season": "The Apple Podcasts season number.",
+ "itunes_episode_type": "The Apple Podcasts episode type: full, trailer, or bonus.",
+ "custom_link": "A custom link used as the episode website in the RSS feed.",
+ "cover_url": "Public URL of the episode cover image, if any.",
+ "audio_url": "Public URL to listen to or download the episode audio.",
+ "audio_preview_url": "Private URL to preview the episode audio before publication.",
+ "video_url": "Public URL to watch or download the episode video.",
+ "video_preview_url": "Private URL to preview the episode video before publication.",
+ "processing": "Status of the processing jobs associated with the episode.",
+ "resources": "Status of the child resources associated with the episode.",
+ "locations": "Locations assigned to the episode.",
+ "keywords": "Keywords assigned to the episode.",
+ "apple_episode_access_type": "Apple Delegated Delivery access type of the episode.",
+ "dashboard_url": "The RSS.com dashboard URL for the episode.",
+ "website_url": "The RSS.com website URL for the episode.",
+ "youtube_video_url": "The URL of the YouTube video generated from the episode.",
+ "transcript_url": "The URL of the transcript for the episode.",
+ "alternate_enclosures": "Alternate media enclosures for the episode.",
+ "ai_content": "Whether the episode was made with AI.",
+ "guid": "The GUID of the episode, used in the RSS feed.",
+ },
+ },
+ "categories": {
+ "description": "A podcast category available on RSS.com (Apple Podcasts taxonomy).",
+ "docs_url": "https://api.rss.com/v4/docs",
+ "columns": {
+ "id": "The unique ID of the category.",
+ "label": "The category label.",
+ "localized_label": "The category label localized to your account language.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/rss.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/rss.py
new file mode 100644
index 000000000000..355582896127
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/rss.py
@@ -0,0 +1,200 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.settings import RSS_ENDPOINTS
+
+RSS_BASE_URL = "https://api.rss.com/v4"
+# The episodes endpoint accepts a `limit` of up to 100 (default 100); the largest page minimises
+# round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
+# validates access to every endpoint.
+DEFAULT_PROBE_PATH = "/podcasts"
+
+
+class RssRetryableError(Exception):
+ pass
+
+
+class RssResumeConfig:
+ """Resume state for the per-podcast episodes fan-out.
+
+ `podcasts` and `categories` are single unpaginated requests, so only the episodes endpoint
+ persists state: which podcasts are fully synced and the next page of the podcast in flight.
+ Page-number pagination with `order=oldest` is deterministic, so a crashed sync resumes from the
+ page after the last one yielded; merge dedupes re-pulled rows on the primary key.
+ """
+
+ completed_podcast_ids: list[int] = dataclasses.field(default_factory=list)
+ current_podcast_id: int | None = None
+ next_page: int = 1
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"X-Api-Key": api_key, "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((RssRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_list(
+ session: requests.Session,
+ path: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ response = session.get(
+ f"{RSS_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RssRetryableError(f"RSS.com API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"RSS.com API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Every RSS.com list endpoint returns a bare JSON array of objects.
+ if not isinstance(data, list):
+ raise RssRetryableError(f"RSS.com returned an unexpected payload for {path}: {type(data).__name__}")
+
+ return data
+
+
+def _get_episode_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RssResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = RSS_ENDPOINTS["episodes"]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ completed = set(resume.completed_podcast_ids) if resume else set()
+ if resume:
+ logger.debug(f"RSS.com: resuming episodes fan-out, {len(completed)} podcasts already synced")
+
+ podcasts = _fetch_list(session, RSS_ENDPOINTS["podcasts"].path, {}, logger)
+
+ for podcast in podcasts:
+ podcast_id = podcast["id"]
+ if podcast_id in completed:
+ continue
+
+ page = resume.next_page if resume is not None and resume.current_podcast_id == podcast_id else 1
+ path = config.path.format(podcast_id=podcast_id)
+
+ while True:
+ # `order=oldest` gives stable append-only ordering: episodes published mid-sync land on
+ # the final pages instead of shifting every earlier page boundary by one.
+ items = _fetch_list(session, path, {"page": page, "limit": PAGE_SIZE, "order": "oldest"}, logger)
+ if items:
+ # Episode rows don't carry their parent id, so inject it — it is part of the primary
+ # key and what users join back to the podcasts table on.
+ yield [{**item, "podcast_id": podcast_id} for item in items]
+
+ # A short or empty page marks the end of this podcast's episodes.
+ if len(items) < PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages
+ # are persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(
+ RssResumeConfig(
+ completed_podcast_ids=sorted(completed),
+ current_podcast_id=podcast_id,
+ next_page=page,
+ )
+ )
+
+ completed.add(podcast_id)
+ resumable_source_manager.save_state(RssResumeConfig(completed_podcast_ids=sorted(completed)))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RssResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = RSS_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ if config.fan_out_podcasts:
+ yield from _get_episode_rows(session, logger, resumable_source_manager)
+ return
+
+ # podcasts / categories: a single unpaginated request returns the whole collection.
+ items = _fetch_list(session, config.path, {}, logger)
+ if items:
+ yield items
+
+
+def rss_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RssResumeConfig],
+) -> SourceResponse:
+ config = RSS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``402``/``403`` auth or plan failure,
+ ``0`` for a connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{RSS_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to RSS.com: {e}"
+
+ if response.status_code in (401, 402, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"RSS.com returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid RSS.com API key"
+ if status == 402:
+ return False, "The RSS.com API is only available on RSS.com Network plans. Upgrade your plan, then reconnect."
+ return False, message or "Could not validate RSS.com API key"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/settings.py
new file mode 100644
index 000000000000..447f496195fe
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/settings.py
@@ -0,0 +1,37 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class RssEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # True for endpoints that accept `page`/`limit` query params. The unpaginated endpoints return
+ # the whole collection in a single response.
+ paginated: bool = False
+ # True for per-podcast endpoints (`{podcast_id}` in the path): the source iterates
+ # `/podcasts` and queries the endpoint once per podcast, injecting `podcast_id` into every row.
+ fan_out_podcasts: bool = False
+
+
+# RSS.com Core API v4 list endpoints (https://api.rss.com/v4/docs). All are full-refresh only: the
+# OpenAPI spec exposes no server-side timestamp filter (`updated_after`/`since`) on any list
+# endpoint, so there is no incremental cursor to advance. `/v4/locations` is excluded — it is a
+# search endpoint that requires a free-text `filter` string, not a listable collection.
+RSS_ENDPOINTS: dict[str, RssEndpointConfig] = {
+ "podcasts": RssEndpointConfig(name="podcasts", path="/podcasts"),
+ "episodes": RssEndpointConfig(
+ name="episodes",
+ path="/podcasts/{podcast_id}/episodes",
+ # The spec does not document episode ids as globally unique, so the injected parent id is
+ # part of the key to keep it unique table-wide across the fan-out.
+ primary_keys=["podcast_id", "id"],
+ paginated=True,
+ fan_out_podcasts=True,
+ ),
+ "categories": RssEndpointConfig(name="categories", path="/categories"),
+}
+
+ENDPOINTS = tuple(RSS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/source.py
index 2e79cea22fc5..88270d10bf77 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/source.py
@@ -1,19 +1,39 @@
-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.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+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.generated_configs import RssSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.rss import (
+ RssResumeConfig,
+ rss_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.settings import ENDPOINTS, RSS_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RssSource(SimpleSource[RssSourceConfig]):
+class RssSource(ResumableSource[RssSourceConfig, RssResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RSS
@@ -22,9 +42,94 @@ class RssSource(SimpleSource[RssSourceConfig]):
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RSS,
- category=DataWarehouseSourceCategory.PRODUCTIVITY,
- label="RSS",
+ category=DataWarehouseSourceCategory.MARKETING___EMAIL,
+ label="RSS.com",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["podcast", "podcasting"],
+ caption="""Enter your RSS.com API key to pull your podcast and episode data into the PostHog Data warehouse.
+
+The RSS.com API is available on Network plans. You can create an API key under **Profile → API Access** in [RSS.com](https://rss.com).
+""",
iconPath="/static/services/rss.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/rss",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ # Hidden until the source has been validated against a live RSS.com Network-plan
+ # account — the API launched in public beta in early 2026 and behavior was verified
+ # against its OpenAPI spec only.
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.rss.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.rss.com": "Your RSS.com API key is invalid or has been revoked. Generate a new key under Profile → API Access, then reconnect.",
+ "402 Client Error: Payment Required for url: https://api.rss.com": "The RSS.com API is only available on RSS.com Network plans. Upgrade your plan, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.rss.com": "Your RSS.com API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: RssSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — the RSS.com API exposes no server-side timestamp
+ # filter on any list endpoint, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: RssSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RssResumeConfig]:
+ return ResumableSourceManager[RssResumeConfig](inputs, RssResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RssSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RssResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in RSS_ENDPOINTS:
+ raise ValueError(f"Unknown RSS.com schema '{inputs.schema_name}'")
+
+ return rss_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/tests/test_rss.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/tests/test_rss.py
new file mode 100644
index 000000000000..dd2b645cb114
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/tests/test_rss.py
@@ -0,0 +1,276 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss import rss
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.rss import (
+ PAGE_SIZE,
+ RssResumeConfig,
+ RssRetryableError,
+ check_access,
+ get_rows,
+ rss_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.settings import ENDPOINTS, RSS_ENDPOINTS
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_list_unwrapped = rss._fetch_list.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: RssResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[RssResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> RssResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: RssResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _episodes(start_id: int, count: int) -> list[dict]:
+ return [{"id": start_id + i, "title": f"ep {start_id + i}"} for i in range(count)]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[tuple[str, int | None], list[dict]],
+ endpoint: str,
+ ) -> tuple[list[dict], list[dict[str, Any]]]:
+ calls: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, path: str, params: dict[str, Any], logger: Any) -> list[dict]:
+ calls.append({"path": path, "params": params})
+ return pages[(path, params.get("page"))]
+
+ monkeypatch.setattr(rss, "_fetch_list", fake_fetch)
+ monkeypatch.setattr(rss, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="rss-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows, calls
+
+ def test_unpaginated_endpoints_are_a_single_request(self, monkeypatch: Any) -> None:
+ # parameterized.expand doesn't compose with pytest fixtures, so loop instead.
+ for endpoint, path in (("podcasts", "/podcasts"), ("categories", "/categories")):
+ manager = _FakeResumableManager()
+ rows, calls = self._collect(manager, monkeypatch, {(path, None): [{"id": 1}, {"id": 2}]}, endpoint)
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert calls == [{"path": path, "params": {}}]
+ assert manager.saved == []
+
+ def test_empty_collection_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, _ = self._collect(manager, monkeypatch, {("/podcasts", None): []}, "podcasts")
+ assert rows == []
+
+ def test_episodes_fan_out_injects_podcast_id_into_every_row(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ ("/podcasts", None): [{"id": 1}, {"id": 2}],
+ ("/podcasts/1/episodes", 1): _episodes(10, 2),
+ ("/podcasts/2/episodes", 1): _episodes(20, 1),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages, "episodes")
+ assert [(r["podcast_id"], r["id"]) for r in rows] == [(1, 10), (1, 11), (2, 20)]
+ # Each finished podcast is marked completed so a resumed sync never re-walks it.
+ assert [s.completed_podcast_ids for s in manager.saved] == [[1], [1, 2]]
+
+ def test_episodes_paginate_with_stable_oldest_order_and_save_state_after_yield(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ ("/podcasts", None): [{"id": 7}],
+ ("/podcasts/7/episodes", 1): _episodes(0, PAGE_SIZE),
+ ("/podcasts/7/episodes", 2): _episodes(PAGE_SIZE, 3),
+ }
+ rows, calls = self._collect(manager, monkeypatch, pages, "episodes")
+ assert len(rows) == PAGE_SIZE + 3
+ episode_calls = [c for c in calls if c["path"] == "/podcasts/7/episodes"]
+ assert all(c["params"]["order"] == "oldest" and c["params"]["limit"] == PAGE_SIZE for c in episode_calls)
+ # Page-cursor state is saved after the full first page, then the podcast is marked complete.
+ assert [(s.current_podcast_id, s.next_page, s.completed_podcast_ids) for s in manager.saved] == [
+ (7, 2, []),
+ (None, 1, [7]),
+ ]
+
+ def test_episodes_resume_skips_completed_podcasts_and_resumes_saved_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(RssResumeConfig(completed_podcast_ids=[1], current_podcast_id=2, next_page=3))
+ # Pages 1 and 2 of podcast 2 (and all of podcast 1) must never be re-fetched on resume.
+ pages = {
+ ("/podcasts", None): [{"id": 1}, {"id": 2}],
+ ("/podcasts/2/episodes", 3): _episodes(30, 1),
+ }
+ rows, calls = self._collect(manager, monkeypatch, pages, "episodes")
+ assert [(r["podcast_id"], r["id"]) for r in rows] == [(2, 30)]
+ assert all(c["path"] != "/podcasts/1/episodes" for c in calls)
+
+ def test_episodes_resume_page_only_applies_to_the_podcast_in_flight(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(RssResumeConfig(completed_podcast_ids=[], current_podcast_id=1, next_page=2))
+ pages = {
+ ("/podcasts", None): [{"id": 1}, {"id": 2}],
+ ("/podcasts/1/episodes", 2): _episodes(10, 1),
+ ("/podcasts/2/episodes", 1): _episodes(20, 1),
+ }
+ rows, _ = self._collect(manager, monkeypatch, pages, "episodes")
+ assert [(r["podcast_id"], r["id"]) for r in rows] == [(1, 10), (2, 20)]
+
+ def test_episodes_no_podcasts_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, calls = self._collect(manager, monkeypatch, {("/podcasts", None): []}, "episodes")
+ assert rows == []
+ assert calls == [{"path": "/podcasts", "params": {}}]
+
+
+class TestFetchList:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(RssRetryableError):
+ _fetch_list_unwrapped(session, "/podcasts", {}, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("payment_required", 402), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_list_unwrapped(session, "/podcasts", {}, MagicMock())
+
+ def test_success_returns_list(self) -> None:
+ session = self._session_returning(200, [{"id": 1}])
+ assert _fetch_list_unwrapped(session, "/podcasts", {}, MagicMock()) == [{"id": 1}]
+
+ def test_non_list_body_is_retryable(self) -> None:
+ session = self._session_returning(200, {"message": "unexpected"})
+ with pytest.raises(RssRetryableError):
+ _fetch_list_unwrapped(session, "/podcasts", {}, MagicMock())
+
+ def test_params_are_forwarded(self) -> None:
+ session = self._session_returning(200, [])
+ _fetch_list_unwrapped(
+ session, "/podcasts/1/episodes", {"page": 2, "limit": 100, "order": "oldest"}, MagicMock()
+ )
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"page": 2, "limit": 100, "order": "oldest"}
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("payment_required", 402, False, 402, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "RSS.com returned HTTP 500"),
+ ]
+ )
+ @patch(f"{rss.__name__}.make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ mock_session.return_value = self._session(response)
+ assert check_access("rss-key") == (expected_status, expected_message)
+
+ @patch(f"{rss.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("rss-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid RSS.com API key"),
+ ("forbidden", 403, False, "Invalid RSS.com API key"),
+ (
+ "payment_required",
+ 402,
+ False,
+ "The RSS.com API is only available on RSS.com Network plans. Upgrade your plan, then reconnect.",
+ ),
+ ("server_error", 500, False, "RSS.com returned HTTP 500"),
+ ]
+ )
+ @patch(f"{rss.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_session.return_value = self._session(response)
+ assert validate_credentials("rss-key") == (expected_valid, expected_message)
+
+
+class TestRssSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = rss_source(
+ api_key="rss-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == RSS_ENDPOINTS[endpoint].primary_keys
+ # Episodes carry no stable creation timestamp (only mutable publish/schedule fields), so we
+ # don't partition any endpoint.
+ assert response.partition_mode is None
+
+ def test_episodes_key_includes_parent_id(self) -> None:
+ # Fan-out child rows aggregate every podcast's episodes into one table; the spec doesn't
+ # document episode ids as globally unique, so the key must include the parent id.
+ assert RSS_ENDPOINTS["episodes"].primary_keys == ["podcast_id", "id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rss/tests/test_rss_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/tests/test_rss_source.py
new file mode 100644
index 000000000000..cdac276cef08
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rss/tests/test_rss_source.py
@@ -0,0 +1,140 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+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.generated_configs import RssSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.rss import RssResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.rss.source import RssSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestRssSource:
+ def setup_method(self) -> None:
+ self.source = RssSource()
+ self.team_id = 123
+ self.config = RssSourceConfig(api_key="rss-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.RSS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Rss"
+ assert config.label == "RSS.com"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Intentionally unreleased until validated against a live RSS.com Network-plan account.
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/rss"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another host.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["episodes"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "episodes"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.rss.com/v4/podcasts",
+ ),
+ (
+ "payment_required",
+ "402 Client Error: Payment Required for url: https://api.rss.com/v4/podcasts",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.rss.com/v4/podcasts/1/episodes?page=1",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.rss.com/v4/podcasts",
+ ),
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://api.rss.com/v4/podcasts",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rss.source.validate_credentials")
+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:
+ # The status-to-message mapping lives in rss.validate_credentials; here we only assert the
+ # source probes with the configured key and returns the delegate's verdict unchanged.
+ mock_validate.return_value = (False, "Invalid RSS.com API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("rss-key")
+ assert result == (False, "Invalid RSS.com API key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is RssResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rss.source.rss_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "episodes"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "rss-key"
+ assert kwargs["endpoint"] == "episodes"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown RSS.com schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)