:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement tvmaze import source (#72625)
Tom Owersa8b192c46289
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 94eaf94a820f..e4c95be13019 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -553,6 +553,7 @@ the row lists both.| trello | HTTP | requests | ✅ || tremendous | HTTP | requests | ✅ || trigger_dev | HTTP | requests | ✅ |+| tvmaze | HTTP | requests + `rest_source.RESTClient` | ✅ || twelve_data | HTTP | requests | ✅ || twelve_labs | HTTP | requests | ✅ || twilio | HTTP | requests | ✅ |@@ -975,7 +976,6 @@ doesn't conflict with concurrent PRs.- tremendous- trustpilot- turso-- tvmaze- twenty- twitter_adsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/canonical_descriptions.pynew file mode 100644index 000000000000..afe88aaf4b3c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/canonical_descriptions.py@@ -0,0 +1,67 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "shows": {+ "description": "Every TV show in the TVmaze database, from the paginated show index.",+ "docs_url": "https://www.tvmaze.com/api#show-index",+ "columns": {+ "id": "Unique TVmaze identifier for the show.",+ "url": "URL of the show's page on tvmaze.com.",+ "name": "Name of the show.",+ "type": "Show type, e.g. Scripted, Reality, Animation, Documentary.",+ "language": "Primary language the show is produced in.",+ "genres": "List of genres the show belongs to.",+ "status": "Airing status, e.g. Running, Ended, To Be Determined, In Development.",+ "runtime": "Scheduled runtime of an episode in minutes.",+ "averageRuntime": "Average runtime across the show's episodes in minutes.",+ "premiered": "Date the show first premiered.",+ "ended": "Date the show ended, if it has.",+ "officialSite": "URL of the show's official website.",+ "schedule": "When the show airs: time of day and days of the week.",+ "rating": "Weighted average of user ratings on TVmaze.",+ "weight": "Popularity weight (0-100) used by TVmaze to rank search results.",+ "network": "Broadcast network the show airs on, including its country.",+ "webChannel": "Streaming/web channel the show airs on, if not a broadcast network.",+ "dvdCountry": "Country of the DVD release ordering, when episodes follow DVD order.",+ "externals": "Identifiers for the show in external databases (IMDb, TheTVDB, TVRage).",+ "image": "URLs of the show's poster image in medium and original sizes.",+ "summary": "Synopsis of the show as HTML.",+ "updated": "UNIX timestamp of when the show was last modified on TVmaze.",+ "_links": "HAL links to related API resources such as the previous and next episode.",+ },+ },+ "people": {+ "description": "Every person (cast and crew) in the TVmaze database, from the paginated person index.",+ "docs_url": "https://www.tvmaze.com/api#people-index",+ "columns": {+ "id": "Unique TVmaze identifier for the person.",+ "url": "URL of the person's page on tvmaze.com.",+ "name": "Name of the person.",+ "country": "Country the person was born in.",+ "birthday": "Date of birth.",+ "deathday": "Date of death, if applicable.",+ "gender": "Gender of the person.",+ "image": "URLs of the person's headshot in medium and original sizes.",+ "updated": "UNIX timestamp of when the person was last modified on TVmaze.",+ "_links": "HAL links to related API resources.",+ },+ },+ "show_updates": {+ "description": "Last-modified timestamp for every show, useful to detect which shows changed between syncs.",+ "docs_url": "https://www.tvmaze.com/api#show-updates",+ "columns": {+ "id": "Unique TVmaze identifier for the show.",+ "updated": "UNIX timestamp of when the show was last modified on TVmaze.",+ },+ },+ "person_updates": {+ "description": "Last-modified timestamp for every person, useful to detect which people changed between syncs.",+ "docs_url": "https://www.tvmaze.com/api#person-updates",+ "columns": {+ "id": "Unique TVmaze identifier for the person.",+ "updated": "UNIX timestamp of when the person was last modified on TVmaze.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/settings.pynew file mode 100644index 000000000000..42692f3f74dc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/settings.py@@ -0,0 +1,51 @@+from dataclasses import dataclass+from typing import Literal++from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.tvmaze.com"++# TVmaze allows at least 20 requests per 10 seconds per IP; the transport-level+# retry already honors 429 + Retry-After, so no extra throttling layer is needed.+TVMazeEndpointKind = Literal["index", "updates"]+++@dataclass+class TVMazeEndpointConfig:+ name: str+ path: str+ # "index" endpoints walk ?page=N (0-indexed) and terminate on the API's+ # documented 404 past the last page; "updates" endpoints return a single+ # {id: last_updated_unix_ts} map in one response.+ kind: TVMazeEndpointKind+++ENDPOINT_CONFIGS: dict[str, TVMazeEndpointConfig] = {+ "shows": TVMazeEndpointConfig(+ name="shows",+ path="/shows",+ kind="index",+ ),+ "people": TVMazeEndpointConfig(+ name="people",+ path="/people",+ kind="index",+ ),+ "show_updates": TVMazeEndpointConfig(+ name="show_updates",+ path="/updates/shows",+ kind="updates",+ ),+ "person_updates": TVMazeEndpointConfig(+ name="person_updates",+ path="/updates/people",+ kind="updates",+ ),+}++ENDPOINTS = tuple(ENDPOINT_CONFIGS)++# TVmaze has no server-side timestamp filter on any endpoint (the /updates maps only+# accept coarse ?since=day|week|month windows, verified against the live API), so+# every table is full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/source.pyindex 4f300deeb6ab..d67f2b8499d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/source.py@@ -1,30 +1,107 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,)-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,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tvmaze import TVMazeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.tvmaze import (+ TVMazeResumeConfig,+ check_connection,+ tvmaze_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TVMazeSource(SimpleSource[TVMazeSourceConfig]):+class TVMazeSource(ResumableSource[TVMazeSourceConfig, TVMazeResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # TVmaze exposes no version token (no /vN/ path, header, or dated release), so the+ # framework's unversioned default applies.+ api_docs_url = "https://www.tvmaze.com/api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TVMAZE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # The public API needs no credentials; a 401/403 means TVmaze is refusing the+ # caller (e.g. an IP-level block), which a retry cannot fix.+ return {+ "401 Client Error": "TVmaze rejected the request. Try again later.",+ "403 Client Error": "TVmaze rejected the request. Try again later.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TVMazeSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: TVMazeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # No credentials to validate — just confirm the public API is reachable.+ return check_connection()++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TVMazeResumeConfig]:+ return ResumableSourceManager[TVMazeResumeConfig](inputs, TVMazeResumeConfig)++ def source_for_pipeline(+ self,+ config: TVMazeSourceConfig,+ resumable_source_manager: ResumableSourceManager[TVMazeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return tvmaze_source(+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.TV_MAZE,category=DataWarehouseSourceCategory.ANALYTICS,- label="TVMaze",+ label="TVmaze",+ caption="Import TV show and people data from the free public TVmaze API. No API key is required. TVmaze data is licensed CC BY-SA, which requires attribution and share-alike.",+ docsUrl="https://posthog.com/docs/cdp/sources/tvmaze",iconPath="/static/services/tvmaze.png",+ keywords=["tv", "television", "tv shows"],fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tests/test_tvmaze.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tests/test_tvmaze.pynew file mode 100644index 000000000000..bf0230c454d4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tests/test_tvmaze.py@@ -0,0 +1,197 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.tvmaze import (+ UPDATES_CHUNK_SIZE,+ TVMazeResumeConfig,+ check_connection,+ tvmaze_source,+)++REST_CLIENT_SESSION_FACTORY = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"+ ".make_tracked_session"+)+TVMAZE_SESSION_FACTORY = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.tvmaze.make_tracked_session"+)+++def _make_http_response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _drive_index(+ endpoint: str, manager: MagicMock, responses: list[Response]+) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(REST_CLIENT_SESSION_FACTORY) as MockSession:+ mock_session = MockSession.return_value+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source = tvmaze_source(+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ pages = list(cast(Iterable[list[dict[str, Any]]], source.items()))+ return sent_params, pages+++class TestIndexPagination:+ """End-to-end pagination + resume behaviour of the show/person indexes."""++ @pytest.mark.parametrize("endpoint", ["shows", "people"])+ def test_walks_pages_until_404_and_skips_empty_pages(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response([{"id": 1}, {"id": 2}]),+ # Deleted records can leave a sparse (empty) page mid-index; it must+ # not terminate the walk — only the documented 404 does.+ _make_http_response([]),+ _make_http_response([{"id": 700}]),+ _make_http_response([], status_code=404),+ ]+ sent_params, pages = _drive_index(endpoint, manager, responses)++ assert [p.get("page") for p in sent_params] == [0, 1, 2, 3]+ assert [row["id"] for page in pages for row in page] == [1, 2, 700]++ def test_saves_next_page_after_each_yielded_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response([{"id": 1}]),+ _make_http_response([{"id": 300}]),+ _make_http_response([], status_code=404),+ ]+ _drive_index("shows", manager, responses)++ # One checkpoint per yielded data page; the terminating 404 page is+ # never checkpointed (there is nothing left to resume to).+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [TVMazeResumeConfig(page=1), TVMazeResumeConfig(page=2)]++ def test_resume_seeds_paginator_with_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = TVMazeResumeConfig(page=7)++ responses = [+ _make_http_response([{"id": 1750}]),+ _make_http_response([], status_code=404),+ ]+ sent_params, _ = _drive_index("shows", manager, responses)++ assert [p.get("page") for p in sent_params] == [7, 8]+ manager.load_state.assert_called_once()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([], status_code=404)]+ _drive_index("shows", manager, responses)++ manager.load_state.assert_not_called()+++class TestUpdatesEndpoints:+ @pytest.mark.parametrize(+ ("endpoint", "expected_path"),+ [+ ("show_updates", "/updates/shows"),+ ("person_updates", "/updates/people"),+ ],+ )+ def test_flattens_id_to_timestamp_map_into_rows(self, endpoint: str, expected_path: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(TVMAZE_SESSION_FACTORY) as MockSession:+ mock_session = MockSession.return_value+ mock_session.get.return_value = _make_http_response({"1": 1631010933, "42": 1631010934})++ source = tvmaze_source(+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ pages = list(cast(Iterable[list[dict[str, Any]]], source.items()))++ requested_url = mock_session.get.call_args.args[0]+ assert requested_url.endswith(expected_path)+ # Ids arrive as JSON object keys (strings) and must land as integers so+ # they can join against the shows/people tables.+ assert pages == [[{"id": 1, "updated": 1631010933}, {"id": 42, "updated": 1631010934}]]++ def test_large_map_is_yielded_in_chunks(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ payload = {str(i): i for i in range(UPDATES_CHUNK_SIZE + 1)}++ with patch(TVMAZE_SESSION_FACTORY) as MockSession:+ MockSession.return_value.get.return_value = _make_http_response(payload)++ source = tvmaze_source(+ endpoint="show_updates",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ pages = list(cast(Iterable[list[dict[str, Any]]], source.items()))++ assert [len(page) for page in pages] == [UPDATES_CHUNK_SIZE, 1]+++class TestCheckConnection:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [+ (200, True),+ (403, False),+ (503, False),+ ],+ )+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:+ with patch(TVMAZE_SESSION_FACTORY) as MockSession:+ response = MagicMock()+ response.status_code = status_code+ MockSession.return_value.get.return_value = response++ valid, error = check_connection()++ assert valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error is not None++ def test_network_error_returns_message(self) -> None:+ with patch(TVMAZE_SESSION_FACTORY) as MockSession:+ MockSession.return_value.get.side_effect = Exception("boom")+ valid, error = check_connection()++ assert valid is False+ assert error == "boom"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tests/test_tvmaze_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tests/test_tvmaze_source.pynew file mode 100644index 000000000000..4c118915681d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tests/test_tvmaze_source.py@@ -0,0 +1,125 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.tvmaze import TVMazeSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.source import TVMazeSource+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.tvmaze import TVMazeResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "shows",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestTVMazeSource:+ def setup_method(self) -> None:+ self.source = TVMazeSource()+ self.team_id = 123+ self.config = TVMazeSourceConfig()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.TVMAZE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "TVMaze"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/tvmaze.png"+ # Doc slug and docsUrl must agree (see /documenting-warehouse-sources).+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/tvmaze"+ # Open public API — the connect form has no credential fields.+ assert config.fields == []++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog: public docs render the table list from get_schemas.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_all_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ # TVmaze has no server-side timestamp filter, so no endpoint may+ # advertise incremental or append sync.+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append 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=["shows"])+ assert [s.name for s in schemas] == ["shows"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # A drifted key silently falls back to LLM enrichment, so keep the+ # curated catalog aligned with the endpoint names.+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS++ @pytest.mark.parametrize(+ "mock_return",+ [+ (True, None),+ (False, "TVmaze API is unreachable (status 503). Try again later."),+ ],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.source.check_connection")+ def test_validate_credentials(self, mock_check: mock.MagicMock, mock_return: tuple[bool, str | None]) -> None:+ mock_check.return_value = mock_return++ assert self.source.validate_credentials(self.config, self.team_id) == mock_return+ mock_check.assert_called_once_with()++ def test_get_non_retryable_errors_covers_auth_rejections(self) -> None:+ # A 401/403 from the public API is an IP-level block that a retry can't+ # fix, so it must be classified non-retryable rather than looping forever.+ errors = self.source.get_non_retryable_errors()+ assert set(errors) == {"401 Client Error", "403 Client Error"}+ assert all(message for message in errors.values())++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is TVMazeResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.source.tvmaze_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="people", team_id=99, job_id="job-xyz")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ endpoint="people",+ team_id=99,+ job_id="job-xyz",+ resumable_source_manager=manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tvmaze.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tvmaze.pynew file mode 100644index 000000000000..9fe04ff82ac8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tvmaze/tvmaze.py@@ -0,0 +1,148 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.tvmaze.settings import BASE_URL, ENDPOINT_CONFIGS++# Rows per yielded batch when flattening the /updates id->timestamp maps (the+# people map holds hundreds of thousands of entries in a single response).+UPDATES_CHUNK_SIZE = 5000+++class TVMazeResumeConfig:+ page: int+++def _make_index_paginator() -> PageNumberPaginator:+ # TVmaze signals the end of an index with a 404 (handled via a response+ # action), not an empty page — deleted records leave gaps, so an empty 200+ # page mid-index must not stop pagination early.+ return PageNumberPaginator(base_page=0, page_param="page", stop_after_empty_page=False)+++def get_resource(endpoint: str) -> EndpointResource:+ config = ENDPOINT_CONFIGS[endpoint]+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": config.path,+ "params": {},+ # The documented index terminator: a page past the last one returns+ # 404 with a JSON body, which ends pagination cleanly.+ "response_actions": [{"status_code": 404, "action": "ignore"}],+ },+ "table_format": "delta",+ }+++def _updates_items(path: str) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session()+ response = session.get(f"{BASE_URL}{path}")+ response.raise_for_status()+ payload = response.json()++ batch: list[dict[str, Any]] = []+ for record_id, updated in payload.items():+ batch.append({"id": int(record_id), "updated": updated})+ if len(batch) >= UPDATES_CHUNK_SIZE:+ yield batch+ batch = []+ if batch:+ yield batch+++def _index_source(+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[TVMazeResumeConfig],+) -> SourceResponse:+ rest_config: RESTAPIConfig = {+ "client": {+ # Open public API — no auth. Traffic still rides the tracked session+ # RESTClient builds by default.+ "base_url": BASE_URL,+ "paginator": _make_index_paginator(),+ },+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [get_resource(endpoint)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Called after each page is yielded, so a crash re-fetches the last page+ # rather than skipping it; the Redis TTL handles cleanup on completion.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(TVMazeResumeConfig(page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ # Index pages are ordered by ascending id; no stable non-null datetime+ # field exists (premiered can be null), so partitioning is skipped.+ sort_mode="asc",+ )+++def tvmaze_source(+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[TVMazeResumeConfig],+) -> SourceResponse:+ endpoint_config = ENDPOINT_CONFIGS[endpoint]++ if endpoint_config.kind == "updates":+ return SourceResponse(+ name=endpoint,+ items=lambda: _updates_items(endpoint_config.path),+ primary_keys=["id"],+ sort_mode="asc",+ )++ return _index_source(endpoint, team_id, job_id, resumable_source_manager)+++def check_connection() -> tuple[bool, str | None]:+ try:+ # The first index page is part of the API contract (and cached at+ # TVmaze's load balancer), unlike any individual show id.+ response = make_tracked_session().get(f"{BASE_URL}/shows", params={"page": 0})+ except Exception as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None++ return False, f"TVmaze API is unreachable (status {response.status_code}). Try again later."