: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 watchmode import source (#72646)
Tom Owersae4a3f113ac7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 928eda0f9fb5..9d114661db94 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -577,6 +577,7 @@ the row lists both.| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ || vultr | HTTP | requests + `rest_source.RESTClient` | ✅ || wasabi | HTTP | requests + `rest_source.RESTClient` | ✅ |+| watchmode | HTTP | requests + `rest_source.RESTClient` | ✅ || webflow | HTTP | requests | ✅ || weights_and_biases | HTTP (GraphQL) | requests | ✅ || windmill | HTTP | requests | ✅ |@@ -986,6 +987,7 @@ doesn't conflict with concurrent PRs.- visma_economic- vwo- waiteraid+- wasabi- watchmode- when_i_work- wikipedia_pageviewsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/watchmode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/watchmode.pyindex 6da88b68d4aa..77e717636a40 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/watchmode.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/watchmode.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass WatchmodeSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/canonical_descriptions.pynew file mode 100644index 000000000000..0cd8f05a51b0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/canonical_descriptions.py@@ -0,0 +1,74 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "titles": {+ "description": "Every movie and TV title in Watchmode's catalog, with external IDs for cross-referencing IMDb and TMDB.",+ "docs_url": "https://api.watchmode.com/docs/",+ "columns": {+ "id": "Watchmode's unique ID for the title.",+ "title": "Name of the title.",+ "year": "Year the title was released.",+ "imdb_id": "IMDb ID for the title.",+ "tmdb_id": "TMDB ID for the title.",+ "tmdb_type": "Whether the TMDB ID refers to a movie or a TV entry.",+ "type": "Type of the title: movie, tv_series, tv_movie, tv_special, tv_miniseries or short_film.",+ },+ },+ "releases": {+ "description": "Titles recently released or coming soon to major streaming services, one row per title per service.",+ "docs_url": "https://api.watchmode.com/docs/",+ "columns": {+ "id": "Watchmode's unique ID for the title.",+ "title": "Name of the title.",+ "type": "Type of the title: movie, tv_series, tv_movie, tv_special, tv_miniseries or short_film.",+ "imdb_id": "IMDb ID for the title.",+ "tmdb_id": "TMDB ID for the title.",+ "tmdb_type": "Whether the TMDB ID refers to a movie or a TV entry.",+ "season_number": "Season number arriving on the service, for TV series releases.",+ "poster_url": "URL of the title's poster image.",+ "source_release_date": "Date the title becomes available on the service.",+ "source_id": "Watchmode ID of the streaming service the title is released on.",+ "source_name": "Name of the streaming service the title is released on.",+ "is_original": "Whether the title is an original production of the streaming service.",+ },+ },+ "sources": {+ "description": "All streaming services Watchmode tracks availability for, with app deep-link schemes and supported regions.",+ "docs_url": "https://api.watchmode.com/docs/",+ "columns": {+ "id": "Watchmode's unique ID for the streaming source.",+ "name": "Name of the streaming source.",+ "type": "How the service offers titles: sub (subscription), free, purchase or tve (TV everywhere).",+ "logo_100px": "URL of the source's logo image.",+ "regions": "Country codes the source is available in.",+ },+ },+ "regions": {+ "description": "Countries Watchmode provides streaming availability data for.",+ "docs_url": "https://api.watchmode.com/docs/",+ "columns": {+ "country": "2-letter country code for the region.",+ "name": "Name of the country.",+ },+ },+ "networks": {+ "description": "TV networks known to Watchmode, usable as filters on the titles endpoint.",+ "docs_url": "https://api.watchmode.com/docs/",+ "columns": {+ "id": "Watchmode's unique ID for the network.",+ "name": "Name of the TV network.",+ "origin_country": "Country the network originates from.",+ "tmdb_id": "TMDB ID for the network.",+ },+ },+ "genres": {+ "description": "Genre names and IDs, usable as filters on the titles endpoint.",+ "docs_url": "https://api.watchmode.com/docs/",+ "columns": {+ "id": "Watchmode's unique ID for the genre.",+ "name": "Name of the genre.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/settings.pynew file mode 100644index 000000000000..3356cc514438--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/settings.py@@ -0,0 +1,74 @@+from dataclasses import dataclass, field+from typing import Any, Optional++from products.warehouse_sources.backend.types import IncrementalField++WATCHMODE_BASE_URL = "https://api.watchmode.com"++# Documented maximum page size for paginated endpoints.+WATCHMODE_PAGE_LIMIT = 250+++@dataclass(frozen=True)+class WatchmodeEndpointConfig:+ name: str+ path: str+ primary_keys: tuple[str, ...]+ # None means the endpoint returns a root-level JSON array with no wrapper object.+ data_selector: Optional[str] = None+ # True only for endpoints whose docs list page/limit params.+ paginated: bool = False+ params: dict[str, Any] = field(default_factory=dict)+++WATCHMODE_ENDPOINTS: dict[str, WatchmodeEndpointConfig] = {+ "titles": WatchmodeEndpointConfig(+ name="titles",+ path="/v1/list-titles/",+ primary_keys=("id",),+ data_selector="titles",+ paginated=True,+ # The API's default sort (relevance_desc) can shift between page fetches; an+ # explicit stable sort avoids page-boundary skips/duplicates. New titles carry+ # recent release dates, so ascending release date keeps earlier pages stable.+ params={"sort_by": "release_date_asc"},+ ),+ "releases": WatchmodeEndpointConfig(+ name="releases",+ path="/v1/releases/",+ # The same title can land on several streaming services within the window, so+ # the title id alone is not unique per row.+ primary_keys=("id", "source_id"),+ data_selector="releases",+ paginated=True,+ ),+ "sources": WatchmodeEndpointConfig(+ name="sources",+ path="/v1/sources/",+ primary_keys=("id",),+ ),+ "regions": WatchmodeEndpointConfig(+ name="regions",+ path="/v1/regions/",+ # Region rows have no id field; the 2-letter country code is the row identity.+ primary_keys=("country",),+ ),+ "networks": WatchmodeEndpointConfig(+ name="networks",+ path="/v1/networks/",+ primary_keys=("id",),+ ),+ "genres": WatchmodeEndpointConfig(+ name="genres",+ path="/v1/genres/",+ primary_keys=("id",),+ ),+}++ENDPOINTS = tuple(WATCHMODE_ENDPOINTS.keys())++# No endpoint gets incremental sync: the catalog endpoints expose no server-side+# timestamp filter, and the /changes/ endpoints (which do take start_date/end_date)+# return bare title-id integers with no per-row timestamp to watermark on, and are+# restricted to paid plans — so every table ships as full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/source.pyindex 5088a287dd00..057202b80584 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/source.py@@ -1,32 +1,119 @@-from typing import cast+from typing import Optional, castfrom 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,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.watchmode import (WatchmodeSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode import (+ WatchmodeResumeConfig,+ validate_credentials as validate_watchmode_credentials,+ watchmode_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WatchmodeSource(SimpleSource[WatchmodeSourceConfig]):+class WatchmodeSource(ResumableSource[WatchmodeSourceConfig, WatchmodeResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://api.watchmode.com/docs/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WATCHMODE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.watchmode.com": "Your Watchmode API key is invalid or expired. Please generate a new key and update the source.",+ "403 Client Error: Forbidden for url: https://api.watchmode.com": "Your Watchmode plan does not allow access to this endpoint. Please check your plan and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: WatchmodeSourceConfig,+ 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: WatchmodeSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_watchmode_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WatchmodeResumeConfig]:+ return ResumableSourceManager[WatchmodeResumeConfig](inputs, WatchmodeResumeConfig)++ def source_for_pipeline(+ self,+ config: WatchmodeSourceConfig,+ resumable_source_manager: ResumableSourceManager[WatchmodeResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return watchmode_source(+ api_key=config.api_key,+ 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.WATCHMODE,category=DataWarehouseSourceCategory.ANALYTICS,label="Watchmode",+ caption="Sync Watchmode's streaming catalog: titles, releases, streaming sources, regions, networks and genres.\n\nYou can find your API key in your [Watchmode dashboard](https://api.watchmode.com/). Syncs count against your Watchmode monthly request quota.",+ keywords=["streaming", "movies", "tv"],+ docsUrl="https://posthog.com/docs/cdp/sources/watchmode",iconPath="/static/services/watchmode.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/tests/test_watchmode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/tests/test_watchmode.pynew file mode 100644index 000000000000..fc16459fb782--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/tests/test_watchmode.py@@ -0,0 +1,213 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.settings import WATCHMODE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode import (+ WatchmodePaginator,+ WatchmodeResumeConfig,+ watchmode_source,+)+++def _make_json_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+++class TestWatchmodePaginator:+ def test_stops_after_total_pages(self) -> None:+ paginator = WatchmodePaginator()++ page_one = _make_json_response({"titles": [{"id": 1}], "total_pages": 2})+ paginator.update_state(page_one, [{"id": 1}])+ # A returned resume state implies there is a next page.+ assert paginator.get_resume_state() == {"page": 2}++ page_two = _make_json_response({"titles": [{"id": 2}], "total_pages": 2})+ paginator.update_state(page_two, [{"id": 2}])+ assert paginator.has_next_page is False+ assert paginator.get_resume_state() is None++ def test_repeated_page_stops_and_discards_duplicate_rows(self) -> None:+ # If an endpoint silently ignores the `page` param, every page returns the same+ # body — without the guard, pagination would never terminate and each loop would+ # sync a duplicate copy of every row.+ paginator = WatchmodePaginator()+ body = {"releases": [{"id": 1, "source_id": 203}]}++ first_data: list[Any] = [{"id": 1, "source_id": 203}]+ paginator.update_state(_make_json_response(body), first_data)+ # A returned resume state implies there is a next page.+ assert paginator.get_resume_state() == {"page": 2}+ assert first_data # first copy of the rows is kept++ repeated_data: list[Any] = [{"id": 1, "source_id": 203}]+ paginator.update_state(_make_json_response(body), repeated_data)+ assert paginator.has_next_page is False+ assert repeated_data == [] # duplicate rows are dropped before the client yields them++ def test_set_resume_state_seeds_first_request(self) -> None:+ paginator = WatchmodePaginator()+ paginator.set_resume_state({"page": 7})++ request = Request(method="GET", url="https://api.watchmode.com/v1/list-titles/")+ paginator.init_request(request)++ assert request.params["page"] == 7+ assert paginator.has_next_page is True+++class TestWatchmodeSourceResumeBehavior:+ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response]+ ) -> tuple[list[dict[str, Any]], list[Any]]:+ # Returns (sent_params, rows): shallow copies of request.params captured at+ # send-time (the Request object is mutated in place between pages) and the+ # flattened yielded rows.+ 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(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = watchmode_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ rows: list[Any] = []+ for page in cast(Iterable[Any], source_response.items()):+ rows.extend(page if isinstance(page, list) else [page])+ return sent_params, rows++ def test_fresh_titles_run_pages_through_and_checkpoints_each_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_json_response({"titles": [{"id": 1}], "total_pages": 3}),+ _make_json_response({"titles": [{"id": 2}], "total_pages": 3}),+ _make_json_response({"titles": [{"id": 3}], "total_pages": 3}),+ ]+ sent_params, rows = self._drive("titles", manager, responses)++ assert [p.get("page") for p in sent_params] == [1, 2, 3]+ assert all(p.get("limit") == 250 for p in sent_params)+ assert all(p.get("sort_by") == "release_date_asc" for p in sent_params)+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [WatchmodeResumeConfig(page=2), WatchmodeResumeConfig(page=3)]++ 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 = WatchmodeResumeConfig(page=5)++ responses = [+ _make_json_response({"titles": [{"id": 50}], "total_pages": 5}),+ ]+ sent_params, _ = self._drive("titles", manager, responses)++ assert [p.get("page") for p in sent_params] == [5]+ manager.load_state.assert_called_once()++ def test_endpoint_ignoring_page_param_terminates_without_duplicate_rows(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ body = {"releases": [{"id": 1, "source_id": 203}, {"id": 1, "source_id": 57}]}+ responses = [_make_json_response(body), _make_json_response(body)]+ sent_params, rows = self._drive("releases", manager, responses)++ assert len(sent_params) == 2+ assert rows == [{"id": 1, "source_id": 203}, {"id": 1, "source_id": 57}]++ def test_sync_requests_do_not_follow_redirects(self) -> None:+ # `requests` replays the `X-API-Key` header across a cross-host redirect, so a+ # dropped `allow_redirects=False` would forward the customer's key off-host.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_redirects: list[Any] = []+ responses = iter([_make_json_response({"titles": [{"id": 1}], "total_pages": 1})])++ def fake_send(request: Any, *_args: Any, **kwargs: Any) -> Response:+ sent_redirects.append(kwargs.get("allow_redirects"))+ return next(responses)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = watchmode_source(+ api_key="test-key",+ endpoint="titles",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ for _ in cast(Iterable[Any], source_response.items()):+ pass++ assert sent_redirects == [False]++ @pytest.mark.parametrize("endpoint", ["sources", "regions", "networks", "genres"])+ def test_reference_endpoints_fetch_a_single_unpaginated_page(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ row = {"id": 1, "country": "US", "name": "row"}+ responses = [_make_json_response([row])]+ sent_params, rows = self._drive(endpoint, manager, responses)++ assert len(sent_params) == 1+ assert "page" not in sent_params[0]+ assert rows == [row]+ manager.save_state.assert_not_called()++ @pytest.mark.parametrize(+ ("endpoint", "expected_primary_keys"),+ [(name, list(config.primary_keys)) for name, config in WATCHMODE_ENDPOINTS.items()],+ )+ def test_source_response_carries_endpoint_primary_keys(+ self, endpoint: str, expected_primary_keys: list[str]+ ) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ source_response = watchmode_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )++ assert source_response.name == endpoint+ assert source_response.primary_keys == expected_primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/tests/test_watchmode_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/tests/test_watchmode_source.pynew file mode 100644index 000000000000..1ffc74993313--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/tests/test_watchmode_source.py@@ -0,0 +1,154 @@+import pytest+from unittest.mock import MagicMock, patch++import requests++from posthog.schema import ReleaseStatus++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.watchmode import (+ WatchmodeSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.source import WatchmodeSource+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode import WatchmodeResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestWatchmodeSource:+ def setup_method(self) -> None:+ self.source = WatchmodeSource()+ self.config = WatchmodeSourceConfig(api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.WATCHMODE++ def test_source_is_released_as_alpha(self) -> None:+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_get_schemas_are_all_full_refresh(self) -> None:+ # No Watchmode endpoint has a server-side timestamp filter usable for incremental+ # sync; flipping one to incremental without such a filter would corrupt syncs.+ schemas = self.source.get_schemas(self.config, team_id=1)++ assert [s.name for s in schemas] == list(ENDPOINTS)+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["titles", "genres"])++ assert {s.name for s in schemas} == {"titles", "genres"}++ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [+ (200, True),+ (401, False),+ (403, False),+ (500, False),+ ],+ )+ def test_validate_credentials_maps_status_codes(self, status_code: int, expected_valid: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode.make_tracked_session"+ ) as mock_make_session:+ response = requests.Response()+ response.status_code = status_code+ mock_make_session.return_value.get.return_value = response++ valid, error = self.source.validate_credentials(self.config, team_id=1)++ assert valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error++ def test_validate_credentials_sends_key_in_header_not_url(self) -> None:+ # The key must ride in the X-API-Key header, never the query string, so it can't+ # leak into access/proxy logs that record request URLs.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode.make_tracked_session"+ ) as mock_make_session:+ response = requests.Response()+ response.status_code = 200+ mock_get = mock_make_session.return_value.get+ mock_get.return_value = response++ self.source.validate_credentials(self.config, team_id=1)++ called_url = mock_get.call_args.args[0] if mock_get.call_args.args else mock_get.call_args.kwargs["url"]+ assert "test-key" not in called_url+ assert "apiKey" not in called_url+ assert mock_get.call_args.kwargs["headers"] == {"X-API-Key": "test-key"}++ def test_validate_credentials_disables_redirects(self) -> None:+ # A cross-host redirect would otherwise replay the `X-API-Key` header off-host,+ # leaking the key; the validation probe must pin redirects off.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode.make_tracked_session"+ ) as mock_make_session:+ response = requests.Response()+ response.status_code = 200+ mock_make_session.return_value.get.return_value = response++ self.source.validate_credentials(self.config, team_id=1)++ assert mock_make_session.call_args.kwargs["allow_redirects"] is False++ def test_validate_credentials_handles_connection_errors(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.watchmode.make_tracked_session"+ ) as mock_make_session:+ mock_make_session.return_value.get.side_effect = requests.ConnectionError("connection refused")++ valid, error = self.source.validate_credentials(self.config, team_id=1)++ assert valid is False+ assert error is not None and "Watchmode" in error++ @pytest.mark.parametrize("status_code", [401, 403])+ def test_auth_http_errors_are_non_retryable(self, status_code: int) -> None:+ # A bad API key must fail the sync permanently instead of retrying forever, so+ # the patterns have to match the exact HTTPError text raise_for_status produces.+ response = requests.Response()+ response.status_code = status_code+ response.url = "https://api.watchmode.com/v1/list-titles/"+ response.reason = "Unauthorized" if status_code == 401 else "Forbidden"++ with pytest.raises(requests.HTTPError) as exc_info:+ response.raise_for_status()++ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(pattern in str(exc_info.value) for pattern in non_retryable_errors)++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WatchmodeResumeConfig++ def test_source_for_pipeline_plumbs_config_and_inputs(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "titles"+ inputs.team_id = 42+ inputs.job_id = "job-1"+ manager = MagicMock(spec=ResumableSourceManager)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.source.watchmode_source"+ ) as mock_source:+ result = self.source.source_for_pipeline(self.config, manager, inputs)++ assert result is mock_source.return_value+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "test-key"+ assert kwargs["endpoint"] == "titles"+ assert kwargs["team_id"] == 42+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is managerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/watchmode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/watchmode.pynew file mode 100644index 000000000000..0069c14e4cb3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/watchmode/watchmode.py@@ -0,0 +1,172 @@+import json+import dataclasses+from typing import Any, Optional++from requests import RequestException, Response++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,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.watchmode.settings import (+ WATCHMODE_BASE_URL,+ WATCHMODE_ENDPOINTS,+ WATCHMODE_PAGE_LIMIT,+)++VALIDATE_CREDENTIALS_TIMEOUT_SECONDS = 15+++class WatchmodeResumeConfig:+ page: int+++class WatchmodePaginator(PageNumberPaginator):+ """Page-number paginator with a repeated-page guard.++ Watchmode paginates with 1-based ``page`` + ``limit`` and reports ``total_pages`` in the+ response body. Pagination support is documented per endpoint but couldn't be verified+ against the live API for every endpoint, so guard against an endpoint that silently+ ignores ``page``: a page whose rows exactly repeat the previous page's is discarded and+ pagination stops, instead of looping forever on identical responses.+ """++ def __init__(self) -> None:+ super().__init__(base_page=1, page=1, page_param="page", total_path="total_pages")+ self._last_page_fingerprint: Optional[int] = None++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if data:+ fingerprint = hash(json.dumps(data, sort_keys=True, default=str))+ if fingerprint == self._last_page_fingerprint:+ self._has_next_page = False+ # The client yields this same list object after update_state; emptying it+ # keeps the duplicate rows out of the pipeline.+ data.clear()+ return+ self._last_page_fingerprint = fingerprint+ super().update_state(response, data)+++def get_resource(name: str) -> EndpointResource:+ config = WATCHMODE_ENDPOINTS[name]++ endpoint: Endpoint = {+ "path": config.path,+ "params": dict(config.params),+ # Fail loud if the response shape changes (or an error envelope arrives on a 200)+ # instead of silently syncing 0 rows or one garbage row.+ "data_selector_required": True,+ }+ if config.data_selector is not None:+ endpoint["data_selector"] = config.data_selector++ if config.paginated:+ params = endpoint.get("params") or {}+ params["limit"] = WATCHMODE_PAGE_LIMIT+ endpoint["paginator"] = WatchmodePaginator()+ else:+ # Reference endpoints (sources, regions, networks, genres) return the full list+ # in one root-level array and document no pagination params.+ endpoint["paginator"] = SinglePagePaginator()++ return {+ "name": name,+ "table_name": name,+ "write_disposition": "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def watchmode_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WatchmodeResumeConfig],+) -> SourceResponse:+ endpoint_config = WATCHMODE_ENDPOINTS[endpoint]++ config: RESTAPIConfig = {+ "client": {+ "base_url": WATCHMODE_BASE_URL,+ "auth": {+ # Watchmode accepts the key as an `apiKey` query param or an `X-API-Key`+ # header. Use the header so the secret never lands in request URLs (and+ # from there into access/proxy logs).+ "type": "api_key",+ "name": "X-API-Key",+ "api_key": api_key,+ "location": "header",+ },+ # `requests` replays custom headers like `X-API-Key` across a cross-host+ # redirect, so a 3xx from upstream could forward the key off-host. Pin+ # redirects off to keep the credential on the validated host.+ "allow_redirects": False,+ },+ "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:+ # Only persist when there's a next page to resume to; the Redis TTL+ # handles cleanup on completion.+ if state and state.get("page"):+ resumable_source_manager.save_state(WatchmodeResumeConfig(page=int(state["page"])))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(endpoint_config.primary_keys),+ )+++def validate_credentials(api_key: str) -> tuple[bool, Optional[str]]:+ """Probe /v1/status/ — a cheap account endpoint that confirms the key is genuine."""+ # `allow_redirects=False`: keep the `X-API-Key` header from being replayed to a+ # redirect target, matching the sync path's credential boundary.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ try:+ response = session.get(+ f"{WATCHMODE_BASE_URL}/v1/status/",+ headers={"X-API-Key": api_key},+ timeout=VALIDATE_CREDENTIALS_TIMEOUT_SECONDS,+ )+ except RequestException as e:+ return False, f"Could not connect to the Watchmode API: {e}"++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Watchmode API key"+ return False, f"Watchmode API returned an unexpected status code: {response.status_code}"