:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the youtube data import source (#115797)
Tom Owers77f2dcf3c2a4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 36b3577aa323..2dc3f86448a1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -909,6 +909,7 @@ the row lists both.| yoco | HTTP | requests + `rest_source.RESTClient` | ✅ || yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || youtube_analytics | HTTP | requests | ✅ |+| youtube_data | HTTP | requests + `rest_source.RESTClient` | ✅ || zapier_supported_storage | HTTP | requests | ✅ || zapsign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1536,7 +1537,6 @@ doesn't conflict with concurrent PRs.- yandex_metrica- yotpo- younium-- youtube_data- zalando_zdirect- zapsign- zellifydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubedata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubedata.pyindex 8d4501a79302..343cd3736ff9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubedata.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubedata.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass YoutubeDataSourceConfig(config.Config):- pass+ api_key: str+ channel_id: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/canonical_descriptions.pynew file mode 100644index 000000000000..adf7ac4064eb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/canonical_descriptions.py@@ -0,0 +1,57 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "channels": {+ "description": "Public metadata, statistics, branding, and related playlists for the selected YouTube channel.",+ "docs_url": "https://developers.google.com/youtube/v3/docs/channels",+ "columns": {+ "id": "The unique YouTube channel ID.",+ "snippet": "The channel title, description, thumbnails, and publication time.",+ "statistics": "The channel view, subscriber, and video counts.",+ "contentDetails": "Related playlists, including the channel uploads playlist.",+ "brandingSettings": "The channel branding settings.",+ },+ },+ "videos": {+ "description": "Public video details and current statistics for videos in the channel uploads playlist.",+ "docs_url": "https://developers.google.com/youtube/v3/docs/videos",+ "columns": {+ "id": "The unique YouTube video ID.",+ "snippet": "The video title, description, channel ID, thumbnails, and publication time.",+ "contentDetails": "The video duration, definition, captions, and region restrictions.",+ "statistics": "The video view, like, and comment counts.",+ "status": "The video upload status, privacy status, and license.",+ },+ },+ "playlists": {+ "description": "Public playlists owned by the selected channel. This list excludes the system uploads playlist.",+ "docs_url": "https://developers.google.com/youtube/v3/docs/playlists",+ "columns": {+ "id": "The YouTube playlist ID.",+ "snippet": "The playlist title, description, channel ID, thumbnails, and creation time.",+ "contentDetails": "The number of items in the playlist.",+ "status": "The playlist privacy status.",+ },+ },+ "playlist_items": {+ "description": "Items in the channel public playlists, including video references and positions.",+ "docs_url": "https://developers.google.com/youtube/v3/docs/playlistItems",+ "columns": {+ "id": "The playlist item ID.",+ "playlist_id": "The parent playlist ID.",+ "snippet": "The item title, playlist position, channel ID, and video reference.",+ "contentDetails": "The video ID and video publication time.",+ "status": "The playlist item privacy status.",+ },+ },+ "comment_threads": {+ "description": "Public comment threads for the channel and its videos. Reply bodies are not included.",+ "docs_url": "https://developers.google.com/youtube/v3/docs/commentThreads",+ "columns": {+ "id": "The comment thread ID.",+ "snippet": "The top-level comment, channel ID, video ID, and total reply count.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/settings.pynew file mode 100644index 000000000000..2f63e5bcc2fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/settings.py@@ -0,0 +1,84 @@+from dataclasses import field+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField+++@frozen+class YoutubeDataEndpoint:+ name: str+ path: str+ part: str+ params: dict[str, str | int] = field(default_factory=dict)+ primary_keys: tuple[str, ...] = ("id",)+ partition_keys: tuple[str, ...] = ("id",)+ partition_mode: Literal["md5"] = "md5"+ partition_count: int = 16+ page_size: int = 50+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ fanout: DependentEndpointConfig | None = None+++# These list methods have no timestamp filter. Their metadata and statistics can change between syncs.+# Request shapes follow the Google discovery spec; they need verification with a live account.+ENDPOINTS: dict[str, YoutubeDataEndpoint] = {+ "channels": YoutubeDataEndpoint(+ name="channels",+ path="channels",+ part="snippet,contentDetails,statistics,brandingSettings",+ ),+ "videos": YoutubeDataEndpoint(+ name="videos",+ path="videos?id={video_id}",+ part="snippet,contentDetails,statistics,status",+ fanout=DependentEndpointConfig(+ parent_name="uploads",+ resolve_param="video_id",+ resolve_field="contentDetails.videoId",+ include_from_parent=[],+ ),+ ),+ "playlists": YoutubeDataEndpoint(+ name="playlists",+ path="playlists",+ part="snippet,contentDetails,status",+ params={"maxResults": 50},+ ),+ "playlist_items": YoutubeDataEndpoint(+ name="playlist_items",+ # Checkpoints use the resolved path, so the query must identify each parent.+ path="playlistItems?playlistId={playlist_id}",+ part="snippet,contentDetails,status",+ params={"maxResults": 50},+ primary_keys=("playlist_id", "id"),+ partition_keys=("playlist_id", "id"),+ fanout=DependentEndpointConfig(+ parent_name="playlists",+ resolve_param="playlist_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "playlist_id"},+ ),+ ),+ "comment_threads": YoutubeDataEndpoint(+ name="comment_threads",+ path="commentThreads",+ part="snippet",+ params={"maxResults": 100, "order": "time", "textFormat": "plainText"},+ ),+}++FANOUT_PARENTS = {+ "playlists": ENDPOINTS["playlists"],+ "uploads": YoutubeDataEndpoint(+ name="uploads", path="playlistItems", part="contentDetails", params={"maxResults": 50}+ ),+}++INCREMENTAL_FIELDS = {name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/source.pyindex 5f49e4631d75..a7d066a079ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/source.py@@ -1,16 +1,54 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.youtubedata import (YoutubeDataSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.youtube_data import (+ ACCESS_ERROR,+ AUTH_ERROR,+ COMMENTS_ERROR,+ NOT_FOUND_ERROR,+ QUOTA_ERROR,+ REQUEST_ERROR,+ YoutubeDataResumeConfig,+ fetch_channel,+ youtube_data_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class YoutubeDataSource(SimpleSource[YoutubeDataSourceConfig]):+class YoutubeDataSource(ResumableSource[YoutubeDataSourceConfig, YoutubeDataResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v3",)+ default_version = "v3"+ api_docs_url = "https://developers.google.com/youtube/v3/revision_history"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.YOUTUBEDATA@@ -20,9 +58,102 @@ class YoutubeDataSource(SimpleSource[YoutubeDataSourceConfig]):return SourceConfig(name=ExternalDataSourceType.YOUTUBEDATA,category=DataWarehouseSourceCategory.ANALYTICS,- label="YouTube Data",+ label="YouTube (Google)",+ caption="Import public data for one YouTube channel. Enable YouTube Data API v3 in your Google Cloud project. "+ "Private data requires OAuth and is not supported. Each sync uses your project's API quota.",+ docsUrl="https://posthog.com/docs/cdp/sources/youtube-data",iconPath="/static/services/youtube_data.png",keywords=["youtube", "yt"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Google API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ placeholder="",+ ),+ SourceFieldInputConfig(+ name="channel_id",+ label="YouTube channel ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ secret=False,+ placeholder="UC...",+ caption="Enter the channel ID that starts with UC. Do not enter a handle or URL.",+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)++ def get_schemas(+ self,+ config: YoutubeDataSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(+ ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default={"comment_threads": False}+ )+ for schema in schemas:+ schema.detected_primary_keys = list(ENDPOINTS[schema.name].primary_keys)+ return schemas++ def validate_credentials(+ self,+ config: YoutubeDataSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, f"Unsupported YouTube table: {schema_name}"+ try:+ fetch_channel(config.api_key, config.channel_id, team_id, self.resolve_api_version(api_version))+ except ValueError as error:+ return False, str(error)+ return True, None++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[YoutubeDataResumeConfig]:+ return ResumableSourceManager(inputs, YoutubeDataResumeConfig)++ def source_for_pipeline(+ self,+ config: YoutubeDataSourceConfig,+ resumable_source_manager: ResumableSourceManager[YoutubeDataResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return youtube_data_source(+ api_key=config.api_key,+ channel_id=config.channel_id,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ message: message+ for message in (+ AUTH_ERROR,+ ACCESS_ERROR,+ QUOTA_ERROR,+ REQUEST_ERROR,+ NOT_FOUND_ERROR,+ COMMENTS_ERROR,+ "YouTube channel was not found.",+ "YouTube uploads playlist was not found.",+ "Unsupported YouTube table:",+ )+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONSdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/tests/test_youtube_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/tests/test_youtube_data.pynew file mode 100644index 000000000000..0b5675e252d2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/tests/test_youtube_data.py@@ -0,0 +1,161 @@+from typing import Any++import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.youtubedata import (+ YoutubeDataSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.source import YoutubeDataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.youtube_data import (+ YoutubeDataResumeConfig,+)+++def driver() -> SourceDriver:+ return SourceDriver(YoutubeDataSource(), YoutubeDataSourceConfig(api_key="fake-api-key", channel_id="UC_example"))+++def page(items: list[dict[str, Any]], next_token: str | None = None) -> ScriptedResponse:+ body: dict[str, Any] = {"items": items}+ if next_token is not None:+ body["nextPageToken"] = next_token+ return ScriptedResponse(json=body)+++ ("table", "filter_name", "path"),+ [+ ("channels", "id", "channels"),+ ("playlists", "channelId", "playlists"),+ ("comment_threads", "allThreadsRelatedToChannelId", "commentThreads"),+ ],+)+def test_public_snapshots_keep_channel_filter_through_empty_pages(+ driver: SourceDriver, table: str, filter_name: str, path: str+) -> None:+ first = {"id": "first", "snippet": {"title": "Example"}}+ last = {"id": "last", "statistics": {"viewCount": "42"}}+ result = driver.run(table, [page([first], "second"), page([], "third"), page([last])])++ assert result.raised is None+ assert result.rows == [first, last]+ assert result.paths == [f"/youtube/v3/{path}"] * 3+ assert result.params(filter_name) == ["UC_example"] * 3+ assert result.params("key") == ["fake-api-key"] * 3+ assert result.params("pageToken") == [None, "second", "third"]+ assert result.params("publishedAfter") == [None] * 3+ assert result.committed_states == [+ YoutubeDataResumeConfig(paginator_state={"cursor": "second"}),+ YoutubeDataResumeConfig(paginator_state={"cursor": "third"}),+ ]+++def test_resume_starts_at_saved_page_token(driver: SourceDriver) -> None:+ result = driver.run(+ "playlists",+ [page([{"id": "last"}])],+ resume_state=YoutubeDataResumeConfig(paginator_state={"cursor": "saved-page"}),+ )++ assert result.raised is None+ assert result.params("pageToken") == ["saved-page"]+ assert result.rows == [{"id": "last"}]++[email protected]("resuming", [False, True])+def test_playlist_items_keep_separate_parent_cursors(driver: SourceDriver, resuming: bool) -> None:+ parent_path = "playlistItems?playlistId=playlist-a"+ resume = YoutubeDataResumeConfig(+ paginator_state={"completed": [], "current": parent_path, "child_state": {"cursor": "next-items"}}+ )+ script = [page([{"id": "playlist-a"}, {"id": "playlist-b"}], "more-playlists")]+ if not resuming:+ script.append(page([{"id": "item-first"}], "next-items"))+ script.extend([page([{"id": "item-last"}]), page([]), page([{"id": "playlist-c"}]), page([{"id": "item-c"}])])++ result = driver.run("playlist_items", script, resume_state=resume if resuming else None)++ assert result.raised is None+ assert result.rows == ([] if resuming else [{"id": "item-first", "playlist_id": "playlist-a"}]) + [+ {"id": "item-last", "playlist_id": "playlist-a"},+ {"id": "item-c", "playlist_id": "playlist-c"},+ ]+ child_requests = [request for request in result.requests if request.path.endswith("/playlistItems")]+ assert [request.param("playlistId") for request in child_requests] == (+ ["playlist-a", "playlist-b", "playlist-c"]+ if resuming+ else ["playlist-a", "playlist-a", "playlist-b", "playlist-c"]+ )+ assert [request.param("pageToken") for request in child_requests] == (+ ["next-items", None, None] if resuming else [None, "next-items", None, None]+ )+ assert all(request.param("playlist_id") is None for request in child_requests)+ assert result.params("pageToken")[-2] == "more-playlists"+ assert result.committed_states[-1].paginator_state == {+ "completed": [+ "playlistItems?playlistId=playlist-a",+ "playlistItems?playlistId=playlist-b",+ "playlistItems?playlistId=playlist-c",+ ],+ "current": None,+ "child_state": None,+ }++[email protected]("resuming", [False, True])+def test_videos_use_uploads_playlist_without_search_or_invalid_page_size(driver: SourceDriver, resuming: bool) -> None:+ resume = YoutubeDataResumeConfig(+ paginator_state={"completed": ["videos?id=video-a"], "current": None, "child_state": None}+ )+ script = [+ page([{"id": "UC_example", "contentDetails": {"relatedPlaylists": {"uploads": "uploads-example"}}}]),+ page([{"contentDetails": {"videoId": "video-a"}}, {"contentDetails": {"videoId": "video-b"}}], "next-uploads"),+ ]+ if not resuming:+ script.append(page([{"id": "video-a", "statistics": {"viewCount": "100"}}]))+ script.extend([page([]), page([{"contentDetails": {"videoId": "video-c"}}]), page([{"id": "video-c"}])])++ result = driver.run("videos", script, resume_state=resume if resuming else None)++ assert result.raised is None+ assert result.rows == ([] if resuming else [{"id": "video-a", "statistics": {"viewCount": "100"}}]) + [+ {"id": "video-c"}+ ]+ video_requests = [request for request in result.requests if request.path.endswith("/videos")]+ assert [request.param("id") for request in video_requests] == (+ ["video-b", "video-c"] if resuming else ["video-a", "video-b", "video-c"]+ )+ assert all(request.param("maxResults") is None for request in video_requests)+ assert all(request.param("video_id") is None for request in video_requests)+ uploads_requests = [request for request in result.requests if request.path.endswith("/playlistItems")]+ assert [request.param("playlistId") for request in uploads_requests] == ["uploads-example"] * 2+ assert [request.param("pageToken") for request in uploads_requests] == [None, "next-uploads"]+ assert not any(request.path.endswith("/search") for request in result.requests)+ assert result.committed_states[-1].paginator_state == {+ "completed": ["videos?id=video-a", "videos?id=video-b", "videos?id=video-c"],+ "current": None,+ "child_state": None,+ }++[email protected]("body", [{"items": []}, {"items": [{"id": "UC_example"}]}])+def test_missing_channel_or_uploads_fails_before_video_discovery(driver: SourceDriver, body: dict[str, Any]) -> None:+ result = driver.run("videos", [ScriptedResponse(json=body)])++ assert isinstance(result.raised, ValueError)+ assert "was not found" in str(result.raised)+ assert result.rows == []+ assert result.paths == ["/youtube/v3/channels"]+++def test_unknown_table_fails_before_network_access(driver: SourceDriver) -> None:+ result = driver.run("unknown", [])++ assert isinstance(result.raised, ValueError)+ assert str(result.raised) == "Unsupported YouTube table: unknown"+ assert result.requests == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/tests/test_youtube_data_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/tests/test_youtube_data_source.pynew file mode 100644index 000000000000..23bd79e08081--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/tests/test_youtube_data_source.py@@ -0,0 +1,77 @@+from typing import Any++import pytest++from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.youtubedata import (+ YoutubeDataSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.source import YoutubeDataSource+++ ("status", "body", "expected_error"),+ [+ (200, {"items": [{"id": "UC_example"}]}, None),+ (200, {"items": []}, "YouTube channel was not found."),+ (+ 400,+ {"error": {"message": "API key not valid. Please pass a valid API key."}},+ "YouTube rejected the request.",+ ),+ (401, {"error": {"errors": [{"reason": "authError"}]}}, "YouTube credentials are invalid or expired."),+ (403, {"error": {"errors": [{"reason": "accessNotConfigured"}]}}, "YouTube access was denied."),+ (403, {"error": {"errors": [{"reason": "quotaExceeded"}]}}, "YouTube quota exceeded."),+ (403, {"error": {"errors": [{"reason": "dailyLimitExceeded"}]}}, "YouTube quota exceeded."),+ (404, {"error": {"errors": [{"reason": "channelNotFound"}]}}, "YouTube could not find the requested data."),+ ],+)+def test_credential_probe_maps_vendor_errors_without_exposing_key(+ status: int, body: dict[str, Any], expected_error: str | None+) -> None:+ config = YoutubeDataSourceConfig(api_key="fake-secret-key", channel_id="UC_example")+ with scripted_network([ScriptedResponse(status=status, json=body)]) as network:+ valid, message = YoutubeDataSource().validate_credentials(config, team_id=1)++ assert valid == (expected_error is None)+ if expected_error is None:+ assert message is None+ else:+ assert message is not None and message.startswith(expected_error)+ assert "fake-secret-key" not in message+ assert len(network.requests_log) == 1+ assert network.requests_log[0].param("part") == "contentDetails"+ assert network.requests_log[0].param("id") == "UC_example"+++def test_unknown_schema_rejects_credentials_without_a_probe() -> None:+ config = YoutubeDataSourceConfig(api_key="fake-secret-key", channel_id="UC_example")+ with scripted_network([]) as network:+ result = YoutubeDataSource().validate_credentials(config, team_id=1, schema_name="unknown")++ assert result == (False, "Unsupported YouTube table: unknown")+ assert network.requests_log == []+++ ("reason", "expected_error"),+ [+ ("commentsDisabled", "YouTube comments are disabled."),+ ("quotaExceeded", "YouTube quota exceeded."),+ ("forbidden", "YouTube access was denied."),+ ],+)+def test_comment_failures_stop_sync_with_actionable_error(reason: str, expected_error: str) -> None:+ config = YoutubeDataSourceConfig(api_key="fake-secret-key", channel_id="UC_example")+ result = SourceDriver(YoutubeDataSource(), config).run(+ "comment_threads", [ScriptedResponse(status=403, json={"error": {"errors": [{"reason": reason}]}})]+ )++ assert isinstance(result.raised, ValueError)+ assert str(result.raised).startswith(expected_error)+ assert "fake-secret-key" not in str(result.raised)+ assert result.rows == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/youtube_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/youtube_data.pynew file mode 100644index 000000000000..5450b975986f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_data/youtube_data.py@@ -0,0 +1,187 @@+from dataclasses import replace+from typing import Any, cast++from posthog.dataclasses import frozen++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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ JSONResponseCursorPaginatorConfig,+ ResponseAction,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_data.settings import (+ ENDPOINTS,+ FANOUT_PARENTS,+)++AUTH_ERROR = "YouTube credentials are invalid or expired. Check your Google API key."+ACCESS_ERROR = "YouTube access was denied. Enable YouTube Data API v3 and check your API key restrictions."+QUOTA_ERROR = "YouTube quota exceeded. Wait for the daily reset or increase the quota in Google Cloud."+REQUEST_ERROR = "YouTube rejected the request. Check your API key and channel ID."+NOT_FOUND_ERROR = "YouTube could not find the requested data. Check that the channel and playlists are public."+COMMENTS_ERROR = "YouTube comments are disabled. Deselect the comment_threads table."++CURSOR_PAGINATOR: JSONResponseCursorPaginatorConfig = {+ "type": "cursor",+ "cursor_path": "nextPageToken",+ "cursor_param": "pageToken",+ "raise_on_repeated_cursor": True,+}++RESPONSE_ACTIONS: list[ResponseAction] = [+ {"status_code": 403, "content": "quotaExceeded", "action": "raise", "message": QUOTA_ERROR},+ {"status_code": 403, "content": "dailyLimitExceeded", "action": "raise", "message": QUOTA_ERROR},+ {"status_code": 403, "content": "commentsDisabled", "action": "raise", "message": COMMENTS_ERROR},+ {"status_code": 400, "action": "raise", "message": REQUEST_ERROR},+ {"status_code": 401, "action": "raise", "message": AUTH_ERROR},+ {"status_code": 403, "action": "raise", "message": ACCESS_ERROR},+ {"status_code": 404, "action": "raise", "message": NOT_FOUND_ERROR},+]+++@frozen+class YoutubeDataResumeConfig:+ paginator_state: dict[str, Any]+++def client_config(api_key: str, api_version: str) -> ClientConfig:+ return {+ "base_url": f"https://www.googleapis.com/youtube/{api_version}/",+ "auth": {"type": "api_key", "name": "key", "api_key": api_key, "location": "query"},+ "paginator": CURSOR_PAGINATOR,+ }+++def resource_config(name: str, channel_id: str) -> EndpointResource:+ settings = ENDPOINTS[name]+ params: dict[str, Any] = {"part": settings.part, **settings.params}+ if name == "channels":+ params["id"] = channel_id+ elif name == "playlists":+ params["channelId"] = channel_id+ elif name == "comment_threads":+ params["allThreadsRelatedToChannelId"] = channel_id++ endpoint: Endpoint = {+ "path": settings.path,+ "params": params,+ "paginator": CURSOR_PAGINATOR,+ "data_selector": "items",+ "data_selector_required": True,+ "response_actions": RESPONSE_ACTIONS,+ }+ return {+ "name": name,+ "table_name": name,+ "primary_key": list(settings.primary_keys),+ "write_disposition": "replace",+ "table_format": "delta",+ "endpoint": endpoint,+ }+++def fetch_channel(api_key: str, channel_id: str, team_id: int, api_version: str) -> dict[str, Any]:+ resource = resource_config("channels", channel_id)+ endpoint = cast(Endpoint, resource["endpoint"])+ endpoint["params"] = {"part": "contentDetails", "id": channel_id}+ endpoint["paginator"] = "single_page"+ config: RESTAPIConfig = {"client": client_config(api_key, api_version), "resources": [resource]}+ for page in rest_api_resource(config, team_id, "youtube_data_channel_probe", None):+ if page:+ return page[0]+ raise ValueError("YouTube channel was not found. Enter a public channel ID, not a handle or URL.")+++def youtube_data_source(+ *,+ api_key: str,+ channel_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[YoutubeDataResumeConfig],+) -> SourceResponse:+ if endpoint not in ENDPOINTS:+ raise ValueError(f"Unsupported YouTube table: {endpoint}")++ initial_state: dict[str, Any] | None = None+ if resumable_source_manager.can_resume():+ saved = resumable_source_manager.load_state()+ if saved is not None:+ initial_state = saved.paginator_state++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None:+ resumable_source_manager.save_state(YoutubeDataResumeConfig(paginator_state=state))++ settings = ENDPOINTS[endpoint]+ fanout = settings.fanout+ if fanout is not None:+ parent = FANOUT_PARENTS[fanout.parent_name]+ parent_params: dict[str, Any] = {"part": parent.part, **parent.params}+ if endpoint == "videos":+ channel = fetch_channel(api_key, channel_id, team_id, api_version)+ resumable_source_manager.safe_point()+ uploads_id = channel.get("contentDetails", {}).get("relatedPlaylists", {}).get("uploads")+ if not uploads_id:+ raise ValueError("YouTube uploads playlist was not found. Check that the channel is public.")+ parent_params["playlistId"] = uploads_id+ else:+ parent_params["channelId"] = channel_id+ endpoint_extra: Endpoint = {+ "data_selector": "items",+ "data_selector_required": True,+ "response_actions": RESPONSE_ACTIONS,+ "paginator": CURSOR_PAGINATOR,+ }+ selected = build_dependent_resource(+ endpoint_configs={**FANOUT_PARENTS, **ENDPOINTS},+ child_endpoint=endpoint,+ fanout=replace(fanout, parent_params=parent_params),+ client_config=client_config(api_key, api_version),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra=endpoint_extra,+ child_endpoint_extra={**endpoint_extra, "paginator": "single_page"}+ if endpoint == "videos"+ else endpoint_extra,+ child_params_extra={"part": settings.part, **settings.params},+ page_size_param=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ )+ else:+ config: RESTAPIConfig = {+ "client": client_config(api_key, api_version),+ "resources": [resource_config(endpoint, channel_id)],+ }+ selected = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ )+ return SourceResponse(+ name=endpoint,+ items=lambda: selected,+ primary_keys=list(settings.primary_keys),+ partition_keys=list(settings.partition_keys),+ partition_mode=settings.partition_mode,+ partition_count=settings.partition_count,+ on_complete=resumable_source_manager.clear_state,+ )