: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 youtube_analytics source (#73785)
Tom Owersfdd0561e2db9
diff --git a/frontend/public/services/youtube_analytics.png b/frontend/public/services/youtube_analytics.pngindex a22df77a65b0..a5bda7d92a85 100644Binary files a/frontend/public/services/youtube_analytics.png and b/frontend/public/services/youtube_analytics.png differdiff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex cc23d7ab73c4..cef919656890 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -92,6 +92,7 @@ export interface integrationsLogicValues {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics')[]) => IntegrationType[]githubAvailableInstallations: GitHubAvailableInstallationApi[] | null@@ -174,6 +175,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'searchParams: any}linkExistingGithubInstallation: (installationId?: string) => string@@ -287,6 +289,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -340,6 +343,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any}@@ -410,6 +414,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: {callback: ((integration: IntegrationType) => void) | undefined@@ -467,6 +472,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: {callback: ((integration: IntegrationType) => void) | undefined@@ -517,6 +523,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}openSetupModal: (integration?: IntegrationType,@@ -577,7 +584,8 @@ export interface integrationsLogicActions {| 'stripe'| 'tiktok-ads'| 'twilio'- | 'vercel',+ | 'vercel'+ | 'youtube-analytics',payload?: {kind: IntegrationKind}@@ -624,6 +632,7 @@ export interface integrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'payload?: {kind: IntegrationKind}@@ -689,6 +698,7 @@ export interface integrationsLogicMeta {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics')[]) => IntegrationType[]slackAvailable: (preflight: PreflightStatus | null) => boolean | undefineddiff --git a/frontend/src/lib/integrations/utils.ts b/frontend/src/lib/integrations/utils.tsindex d784a320f148..b29aa9b3b3a3 100644--- a/frontend/src/lib/integrations/utils.ts+++ b/frontend/src/lib/integrations/utils.ts@@ -40,6 +40,7 @@ import IconStripe from 'public/services/stripe.png'import IconTikTok from 'public/services/tiktok.png'import IconTwilio from 'public/services/twilio.png'import IconVercel from 'public/services/vercel.png'+import IconYouTubeAnalytics from 'public/services/youtube_analytics.png'/*** Where a user started an integration connect flow. Reported as the `surface` property on@@ -106,6 +107,7 @@ export const ICONS: Record<IntegrationKind, any> = {'aws-s3': IconAwsS3,'s3-compatible': IconS3Compatible,snowflake: IconSnowflake,+ 'youtube-analytics': IconYouTubeAnalytics,}// Brand marks that are solid black/monochrome on a transparent background — they vanish against a dark@@ -154,6 +156,8 @@ export const getIntegrationNameFromKind = (kind: string): string => {return 'AWS S3'case 's3-compatible':return 'S3-compatible storage'+ case 'youtube-analytics':+ return 'YouTube Analytics'default:return capitalizeFirstLetter(kind)}diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 67adc2a989ce..83a2226b110a 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -29342,7 +29342,8 @@"postgresql","aws-s3","s3-compatible",- "snowflake"+ "snowflake",+ "youtube-analytics"],"type": "string"},diff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.tsindex 5f87a978bd65..253c15211069 100644--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts@@ -55,6 +55,7 @@ export interface organizationIntegrationsLogicValues {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics')[]) => IntegrationType[]organizationIntegrations: IntegrationType[] | null@@ -126,6 +127,7 @@ export interface organizationIntegrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -179,6 +181,7 @@ export interface organizationIntegrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any}@@ -233,6 +236,7 @@ export interface organizationIntegrationsLogicMeta {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics')[]) => IntegrationType[]}diff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.tsindex 2067b447ae91..7cc764d0bd3a 100644--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts@@ -161,6 +161,7 @@ export interface personalIntegrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -214,6 +215,7 @@ export interface personalIntegrationsLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any} // integrationsLogicdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 292ec096719e..48f82a1839d5 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5522,6 +5522,7 @@ export const INTEGRATION_KINDS = ['aws-s3','s3-compatible','snowflake',+ 'youtube-analytics',] as constexport type IntegrationKind = (typeof INTEGRATION_KINDS)[number]diff --git a/posthog/migrations/1306_add_youtube_analytics_integration_kind.py b/posthog/migrations/1306_add_youtube_analytics_integration_kind.pynew file mode 100644index 000000000000..066ffde842df--- /dev/null+++ b/posthog/migrations/1306_add_youtube_analytics_integration_kind.py@@ -0,0 +1,68 @@+# Generated by Django 5.2.14 on 2026-08-05 12:00++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1305_alter_identityproviderconfig_saml_relay_state_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="integration",+ name="kind",+ field=models.CharField(+ choices=[+ ("anthropic", "Anthropic"),+ ("apns", "Apple Push"),+ ("aws-redshift", "Aws Redshift"),+ ("aws-s3", "Aws S3"),+ ("azure-blob", "Azure Blob"),+ ("bing-ads", "Bing Ads"),+ ("clickup", "Clickup"),+ ("customerio-app", "Customerio App"),+ ("customerio-track", "Customerio Track"),+ ("customerio-webhook", "Customerio Webhook"),+ ("databricks", "Databricks"),+ ("email", "Email"),+ ("firebase", "Firebase"),+ ("github", "Github"),+ ("gitlab", "Gitlab"),+ ("google-ads", "Google Ads"),+ ("google-analytics", "Google Analytics"),+ ("google-calendar", "Google Calendar"),+ ("google-cloud-service-account", "Google Cloud Service Account"),+ ("google-cloud-storage", "Google Cloud Storage"),+ ("google-pubsub", "Google Pubsub"),+ ("google-search-console", "Google Search Console"),+ ("google-sheets", "Google Sheets"),+ ("hubspot", "Hubspot"),+ ("instagram", "Instagram"),+ ("intercom", "Intercom"),+ ("jira", "Jira"),+ ("linear", "Linear"),+ ("linkedin-ads", "Linkedin Ads"),+ ("meta-ads", "Meta Ads"),+ ("pardot", "Pardot"),+ ("pinterest-ads", "Pinterest Ads"),+ ("postgresql", "Postgresql"),+ ("posthog", "Posthog"),+ ("reddit-ads", "Reddit Ads"),+ ("resend", "Resend"),+ ("s3-compatible", "S3 Compatible"),+ ("salesforce", "Salesforce"),+ ("slack", "Slack"),+ ("slack-posthog-code", "Slack Posthog Code"),+ ("snapchat", "Snapchat"),+ ("snowflake", "Snowflake"),+ ("stripe", "Stripe"),+ ("tiktok-ads", "Tiktok Ads"),+ ("twilio", "Twilio"),+ ("vercel", "Vercel"),+ ("youtube-analytics", "Youtube Analytics"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 6deaba69dbd4..aa8e754276a8 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1305_alter_identityproviderconfig_saml_relay_state_and_more+1306_add_youtube_analytics_integration_kinddiff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex b2dd4ce9e8f5..14d15ce838a9 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -599,6 +599,7 @@ class Integration(models.Model):TIKTOK_ADS = "tiktok-ads"TWILIO = "twilio"VERCEL = "vercel"+ YOUTUBE_ANALYTICS = "youtube-analytics"team = models.ForeignKey("Team", on_delete=models.CASCADE)@@ -881,6 +882,7 @@ class OauthIntegration:"pinterest-ads","stripe","resend",+ "youtube-analytics",]integration: Integration@@ -1106,6 +1108,30 @@ class OauthIntegration:id_path="sub",name_path="email",)+ elif kind == "youtube-analytics":+ if not settings.YOUTUBE_ANALYTICS_APP_CLIENT_ID or not settings.YOUTUBE_ANALYTICS_APP_CLIENT_SECRET:+ raise NotImplementedError("YouTube Analytics app not configured")++ return OauthConfig(+ authorize_url="https://accounts.google.com/o/oauth2/v2/auth",+ # forces the consent screen, otherwise we won't receive a refresh token+ additional_authorize_params={"access_type": "offline", "prompt": "consent"},+ token_info_url="https://openidconnect.googleapis.com/v1/userinfo",+ token_info_config_fields=["sub", "email"],+ token_url="https://oauth2.googleapis.com/token",+ client_id=settings.YOUTUBE_ANALYTICS_APP_CLIENT_ID,+ client_secret=settings.YOUTUBE_ANALYTICS_APP_CLIENT_SECRET,+ # `yt-analytics.readonly` reads the reports; `youtube.readonly` lists the account's+ # channels so the user picks one instead of hunting for its ID. Channel reports carry+ # no revenue metrics, so `yt-analytics-monetary.readonly` is deliberately not asked for.+ scope=(+ "https://www.googleapis.com/auth/yt-analytics.readonly "+ "https://www.googleapis.com/auth/youtube.readonly "+ "https://www.googleapis.com/auth/userinfo.email"+ ),+ id_path="sub",+ name_path="email",+ )elif kind == "snapchat":if not settings.SNAPCHAT_APP_CLIENT_ID or not settings.SNAPCHAT_APP_CLIENT_SECRET:raise NotImplementedError("Snapchat app not configured")diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex efc0c388bb07..20dbf8bba239 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -4705,6 +4705,37 @@ class TestPardotIntegrationModel(BaseTest):assert integration.config["expires_in"] == 3600+@override_settings(+ YOUTUBE_ANALYTICS_APP_CLIENT_ID="youtube-client-id",+ YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="youtube-client-secret",+)+class TestYouTubeAnalyticsIntegrationModel(BaseTest):+ def test_oauth_config(self):+ config = OauthIntegration.oauth_config_for_kind("youtube-analytics")++ assert config.authorize_url == "https://accounts.google.com/o/oauth2/v2/auth"+ assert config.token_url == "https://oauth2.googleapis.com/token"+ assert config.client_id == "youtube-client-id"+ assert config.client_secret == "youtube-client-secret"+ assert config.id_path == "sub"+ assert config.name_path == "email"+ # A refresh token only comes back when consent is forced, and the sync depends on one.+ assert config.additional_authorize_params == {"access_type": "offline", "prompt": "consent"}++ def test_oauth_config_requests_analytics_and_channel_read_scopes(self):+ scopes = set(OauthIntegration.oauth_config_for_kind("youtube-analytics").scope.split())++ assert "https://www.googleapis.com/auth/yt-analytics.readonly" in scopes+ assert "https://www.googleapis.com/auth/youtube.readonly" in scopes+ # Channel reports carry no revenue metrics, so the monetary scope is never asked for.+ assert "https://www.googleapis.com/auth/yt-analytics-monetary.readonly" not in scopes++ @override_settings(YOUTUBE_ANALYTICS_APP_CLIENT_ID="", YOUTUBE_ANALYTICS_APP_CLIENT_SECRET="")+ def test_oauth_config_unconfigured_raises(self):+ with pytest.raises(NotImplementedError, match="YouTube Analytics app not configured"):+ OauthIntegration.oauth_config_for_kind("youtube-analytics")++@override_settings(INSTAGRAM_APP_CLIENT_ID="instagram-client-id", INSTAGRAM_APP_CLIENT_SECRET="instagram-client-secret")class TestInstagramIntegrationModel(BaseTest):def test_oauth_config(self):diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 142403ba85e3..c84d6b6eba3e 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2961,6 +2961,7 @@ class IntegrationKind(StrEnum):AWS_S3 = "aws-s3"S3_COMPATIBLE = "s3-compatible"SNOWFLAKE = "snowflake"+ YOUTUBE_ANALYTICS = "youtube-analytics"class IntervalType(StrEnum):diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex d075cae06776..e1a0d29c7e9e 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -40,6 +40,11 @@ GOOGLE_ANALYTICS_APP_CLIENT_SECRET = get_from_env("GOOGLE_ANALYTICS_APP_CLIENT_SGOOGLE_CALENDAR_APP_CLIENT_ID = get_from_env("GOOGLE_CALENDAR_APP_CLIENT_ID", "")GOOGLE_CALENDAR_APP_CLIENT_SECRET = get_from_env("GOOGLE_CALENDAR_APP_CLIENT_SECRET", "")+# Registered in the Google Cloud console with the YouTube Analytics API and the YouTube Data API+# enabled. Empty defaults keep the app importable and the connector dormant until the client exists.+YOUTUBE_ANALYTICS_APP_CLIENT_ID = get_from_env("YOUTUBE_ANALYTICS_APP_CLIENT_ID", "")+YOUTUBE_ANALYTICS_APP_CLIENT_SECRET = get_from_env("YOUTUBE_ANALYTICS_APP_CLIENT_SECRET", "")+SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = get_from_env("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", "")SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = get_from_env("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", "")diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.tsindex 20fbaaa10a52..046d20ac6b21 100644--- a/products/alerts/frontend/logic/alertNotificationLogic.ts+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts@@ -117,6 +117,7 @@ export interface alertNotificationLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -170,6 +171,7 @@ export interface alertNotificationLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any} // integrationsLogicdiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 3731509d061c..c003c21025a8 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -4795,6 +4795,7 @@ export const IntegrationKindApi = {AwsS3: 'aws-s3',S3Compatible: 's3-compatible',Snowflake: 'snowflake',+ YoutubeAnalytics: 'youtube-analytics',} as constexport interface ErrorTrackingExternalReferenceIntegrationApi {diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 7d28aeb90794..fafdfdaa8ca4 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -197,6 +197,7 @@ export interface RoleLookupResponseApi {* * `tiktok-ads` - Tiktok Ads* * `twilio` - Twilio* * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics*/export type IntegrationKindEnumApi = (typeof IntegrationKindEnumApi)[keyof typeof IntegrationKindEnumApi]@@ -247,6 +248,7 @@ export const IntegrationKindEnumApi = {TiktokAds: 'tiktok-ads',Twilio: 'twilio',Vercel: 'vercel',+ YoutubeAnalytics: 'youtube-analytics',} as const/**@@ -514,7 +516,8 @@ export interface IntegrationAccessRequestApi {* * `stripe` - Stripe* * `tiktok-ads` - Tiktok Ads* * `twilio` - Twilio- * * `vercel` - Vercel */+ * * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics */kind: IntegrationKindEnumApi/*** Explanation from the requester of why this integration is needed. Shown to admins in the notification email.@@ -677,6 +680,7 @@ export type IntegrationsListParams = {* * `tiktok-ads` - Tiktok Ads* * `twilio` - Twilio* * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics*/kind?: IntegrationsListKind/**@@ -738,6 +742,7 @@ export const IntegrationsListKind = {TiktokAds: 'tiktok-ads',Twilio: 'twilio',Vercel: 'vercel',+ YoutubeAnalytics: 'youtube-analytics',} as constexport type IntegrationsChannelsRetrieveParams = {diff --git a/products/integrations/frontend/generated/api.zod.ts b/products/integrations/frontend/generated/api.zod.tsindex 7cb41e6a8ba2..1a98db40eedb 100644--- a/products/integrations/frontend/generated/api.zod.ts+++ b/products/integrations/frontend/generated/api.zod.ts@@ -108,9 +108,10 @@ export const IntegrationsCreateBody = /* @__PURE__ */ zod'tiktok-ads','twilio','vercel',+ 'youtube-analytics',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'),config: zod.unknown().optional(),})@@ -166,10 +167,11 @@ export const IntegrationsEmailPartialUpdateBody = /* @__PURE__ */ zod'tiktok-ads','twilio','vercel',+ 'youtube-analytics',]).optional().describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'),config: zod.unknown().optional(),})@@ -225,9 +227,10 @@ export const IntegrationsEmailVerifyCreateBody = /* @__PURE__ */ zod'tiktok-ads','twilio','vercel',+ 'youtube-analytics',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'),config: zod.unknown().optional(),})@@ -290,9 +293,10 @@ export const IntegrationsDomainConnectApplyUrlCreateBody = /* @__PURE__ */ zod'tiktok-ads','twilio','vercel',+ 'youtube-analytics',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'),config: zod.unknown().optional(),})@@ -402,12 +406,13 @@ export const IntegrationsRequestAccessCreateBody = /* @__PURE__ */ zod.object({'tiktok-ads','twilio','vercel',+ 'youtube-analytics',]).describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics').describe(- "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel"+ "The kind of integration the member is requesting be connected (e.g. 'slack', 'github').\n\n\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics"),reason: zod.string()diff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.tsindex d63033d14225..ace5b24bb9d4 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts@@ -112,6 +112,7 @@ export interface logsAlertNotificationLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -165,6 +166,7 @@ export interface logsAlertNotificationLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any} // integrationsLogicdiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex b00f17dc2cc8..0e5fad12f590 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -165,6 +165,7 @@ export interface taskTrackerSceneLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -218,6 +219,7 @@ export interface taskTrackerSceneLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any} // integrationsLogicdiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex e19882b296db..31ad1c03b59a 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -4034,6 +4034,7 @@ export const IntegrationKindApi = {AwsS3: 'aws-s3',S3Compatible: 's3-compatible',Snowflake: 'snowflake',+ YoutubeAnalytics: 'youtube-analytics',} as constexport interface ErrorTrackingExternalReferenceIntegrationApi {diff --git a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.tsindex 47cfd435e26a..8ecbc5daf2f9 100644--- a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts@@ -101,6 +101,7 @@ export interface visualReviewSettingsSceneLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[],payload?: any) => {@@ -154,6 +155,7 @@ export interface visualReviewSettingsSceneLogicActions {| 'tiktok-ads'| 'twilio'| 'vercel'+ | 'youtube-analytics'}[]payload?: any} // integrationsLogicdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3b87db94acd3..21747de17dff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -695,6 +695,7 @@ the row lists both.| xendit | HTTP | requests + `rest_source.RESTClient` | ✅ || xmatters | HTTP | requests | ✅ || yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |+| youtube_analytics | HTTP | requests | ✅ || zapier_supported_storage | HTTP | requests | ✅ || zapsign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1452,7 +1453,6 @@ doesn't conflict with concurrent PRs.- yoco- yotpo- younium-- youtube_analytics- youtube_data- zalando_zdirect- zapsigndiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubeanalytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubeanalytics.pyindex 724619ae8890..e20b043697fe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubeanalytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/youtubeanalytics.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass YouTubeAnalyticsSourceConfig(config.Config):- pass+ channel_id: str+ youtube_analytics_integration_id: int = config.value(converter=config.str_to_int)+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.pynew file mode 100644index 000000000000..aee7795445f6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/canonical_descriptions.py@@ -0,0 +1,155 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (+ CHANNEL_DAILY,+ DEMOGRAPHICS,+ DEVICE_TYPES,+ GEOGRAPHY,+ OPERATING_SYSTEMS,+ PLAYBACK_LOCATIONS,+ SHARING_SERVICES,+ SUBSCRIBED_STATUS,+ TOP_VIDEOS,+ TRAFFIC_SOURCES,+)++_METRICS_DOCS_URL = "https://developers.google.com/youtube/analytics/metrics"+_DIMENSIONS_DOCS_URL = "https://developers.google.com/youtube/analytics/dimensions"++_DAY = "The date the activity occurred, as UTC midnight."+_VIEWS = "The number of times the channel's videos were viewed."+_ESTIMATED_MINUTES_WATCHED = "The number of minutes that users watched the channel's videos."+_AVERAGE_VIEW_DURATION = "The average length, in seconds, of a video playback."+_AVERAGE_VIEW_PERCENTAGE = "The average percentage of a video watched during a playback."+_SUBSCRIBERS_GAINED = "The number of times that users subscribed to the channel."+_SUBSCRIBERS_LOST = "The number of times that users unsubscribed from the channel."+_LIKES = "The number of times that users indicated they liked a video by giving it a positive rating."+_DISLIKES = "The number of times that users indicated they disliked a video by giving it a negative rating."+_COMMENTS = "The number of times that users commented on a video."+_SHARES = "The number of times that users shared a video through the Share button."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ CHANNEL_DAILY: {+ "description": "Daily channel-level user activity: views, watch time, engagement and subscriber changes.",+ "docs_url": _METRICS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "views": _VIEWS,+ "redViews": "The number of times the channel's videos were viewed by YouTube Premium members.",+ "comments": _COMMENTS,+ "likes": _LIKES,+ "dislikes": _DISLIKES,+ "shares": _SHARES,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ "estimatedRedMinutesWatched": "The number of minutes that YouTube Premium members watched the channel's videos.",+ "averageViewDuration": _AVERAGE_VIEW_DURATION,+ "averageViewPercentage": _AVERAGE_VIEW_PERCENTAGE,+ "subscribersGained": _SUBSCRIBERS_GAINED,+ "subscribersLost": _SUBSCRIBERS_LOST,+ "videosAddedToPlaylists": "The number of times the channel's videos were added to any YouTube playlist.",+ "videosRemovedFromPlaylists": "The number of times the channel's videos were removed from any YouTube playlist.",+ },+ },+ TOP_VIDEOS: {+ "description": "The channel's top videos for each day, ranked by watch time (up to 200 videos per day).",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "video": "The YouTube video ID the metrics describe.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ "averageViewDuration": _AVERAGE_VIEW_DURATION,+ "averageViewPercentage": _AVERAGE_VIEW_PERCENTAGE,+ "likes": _LIKES,+ "dislikes": _DISLIKES,+ "comments": _COMMENTS,+ "shares": _SHARES,+ "subscribersGained": _SUBSCRIBERS_GAINED,+ "subscribersLost": _SUBSCRIBERS_LOST,+ },+ },+ TRAFFIC_SOURCES: {+ "description": "Daily views and watch time broken down by the referrer type that led viewers to the videos.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "insightTrafficSourceType": "The referrer type that led viewers to the video, such as YT_SEARCH, SUBSCRIBER or EXT_URL.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ },+ },+ PLAYBACK_LOCATIONS: {+ "description": "Daily views and watch time broken down by the type of page or application where playback occurred.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "insightPlaybackLocationType": "The type of page or application where the playback occurred, such as WATCH, EMBEDDED or CHANNEL.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ },+ },+ DEVICE_TYPES: {+ "description": "Daily views and watch time broken down by the form factor of the device used for playback.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "deviceType": "The physical form factor of the device where the playback occurred, such as MOBILE, DESKTOP or TV.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ },+ },+ OPERATING_SYSTEMS: {+ "description": "Daily views and watch time broken down by the operating system of the playback device.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "operatingSystem": "The software system of the device where the playback occurred, such as ANDROID, IOS or WINDOWS.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ },+ },+ GEOGRAPHY: {+ "description": "Daily views, watch time and subscriber changes broken down by viewer country.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "country": "The ISO 3166-1 alpha-2 country code the metrics are associated with.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ "averageViewDuration": _AVERAGE_VIEW_DURATION,+ "averageViewPercentage": _AVERAGE_VIEW_PERCENTAGE,+ "subscribersGained": _SUBSCRIBERS_GAINED,+ "subscribersLost": _SUBSCRIBERS_LOST,+ },+ },+ DEMOGRAPHICS: {+ "description": "Daily viewer distribution across age group and gender, for signed-in viewers only.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "ageGroup": "The age group of the signed-in viewers, such as age18-24.",+ "gender": "The gender of the signed-in viewers.",+ "viewerPercentage": "The percentage of signed-in viewers that fall into this age group and gender.",+ },+ },+ SHARING_SERVICES: {+ "description": "Daily share counts broken down by the service videos were shared to.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "sharingService": "The service used to share the video, such as WHATSAPP, COPY_PASTE or FACEBOOK.",+ "shares": _SHARES,+ },+ },+ SUBSCRIBED_STATUS: {+ "description": "Daily views and watch time split by whether the viewer was subscribed to the channel.",+ "docs_url": _DIMENSIONS_DOCS_URL,+ "columns": {+ "day": _DAY,+ "subscribedStatus": "Whether the viewer was subscribed to the channel when the activity occurred.",+ "views": _VIEWS,+ "estimatedMinutesWatched": _ESTIMATED_MINUTES_WATCHED,+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.pynew file mode 100644index 000000000000..22c06e029393--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/settings.py@@ -0,0 +1,179 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# The YouTube Analytics API is a single global host; `reports.query` is the only endpoint we call.+YOUTUBE_ANALYTICS_HOST = "https://youtubeanalytics.googleapis.com"++# The YouTube Data API, used only to list the channels the connected account owns.+YOUTUBE_DATA_HOST = "https://www.googleapis.com/youtube/v3"++# Scopes the connected Google account must grant. `yt-analytics-monetary.readonly` is deliberately+# not among them: channel reports carry no revenue metrics, so it would grant nothing we read.+ANALYTICS_SCOPE = "https://www.googleapis.com/auth/yt-analytics.readonly"+YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"+REQUIRED_SCOPES = f"{ANALYTICS_SCOPE} {YOUTUBE_READONLY_SCOPE}"++# `reports.query` caps a response at 200 rows and pages with a 1-based `startIndex`.+MAX_RESULTS_PER_PAGE = 200++# `channels.list?mine=true` returns only the channels the connected account owns, which is one for+# an ordinary Google account, so the API's page maximum covers the list without paging.+MAX_CHANNELS_PER_PAGE = 50++# YouTube keeps revising the most recent days for a while, and the current day is always+# partial, so the sync stops short of today and re-reads a trailing window every run.+DATA_LATENCY_DAYS = 1+REVISION_LOOKBACK_SECONDS = 3 * 24 * 60 * 60++# Reports that carry `day` as a report dimension answer a multi-day window in one request.+# Everything else aggregates over the query window, so those are asked one day at a time.+DAY_DIMENSION_WINDOW_DAYS = 90++# First sync horizon when the user doesn't pin a start date.+DEFAULT_LOOKBACK_DAYS = 365++# Earliest start date we accept. YouTube Analytics has no channel data before 2008, and each+# report walks the range one day (or one 90-day window) at a time, so a date further back just+# fans out empty requests — bound it to keep a stray start date from spawning a runaway backfill.+MIN_START_DATE = "2008-01-01"++CHANNEL_DAILY = "channel_daily"+TOP_VIDEOS = "top_videos"+TRAFFIC_SOURCES = "traffic_sources"+PLAYBACK_LOCATIONS = "playback_locations"+DEVICE_TYPES = "device_types"+OPERATING_SYSTEMS = "operating_systems"+GEOGRAPHY = "geography"+DEMOGRAPHICS = "demographics"+SHARING_SERVICES = "sharing_services"+SUBSCRIBED_STATUS = "subscribed_status"++# Every row carries the day it describes, either from the report's own `day` dimension or+# stamped from the one-day query window.+DAY_FIELD = "day"+++@dataclass(frozen=True)+class YouTubeAnalyticsReportConfig:+ name: str+ # Report dimensions besides the day. Empty means channel-level totals.+ dimensions: tuple[str, ...]+ metrics: tuple[str, ...]+ # True when `day` is requested as a report dimension so one request covers a window of+ # days; False when the report only aggregates over the window and we window per day.+ day_is_dimension: bool = False+ sort: str | None = None+ # `video`-keyed reports are "top N" reports: YouTube caps them at 200 rows and requires+ # an explicit sort, so we take the single page rather than paging into a cap.+ single_page: bool = False++ @property+ def primary_keys(self) -> list[str]:+ return [DAY_FIELD, *self.dimensions]+++YOUTUBE_ANALYTICS_REPORTS: dict[str, YouTubeAnalyticsReportConfig] = {+ CHANNEL_DAILY: YouTubeAnalyticsReportConfig(+ name=CHANNEL_DAILY,+ dimensions=(),+ metrics=(+ "views",+ "redViews",+ "comments",+ "likes",+ "dislikes",+ "shares",+ "estimatedMinutesWatched",+ "estimatedRedMinutesWatched",+ "averageViewDuration",+ "averageViewPercentage",+ "subscribersGained",+ "subscribersLost",+ "videosAddedToPlaylists",+ "videosRemovedFromPlaylists",+ ),+ day_is_dimension=True,+ sort="day",+ ),+ TOP_VIDEOS: YouTubeAnalyticsReportConfig(+ name=TOP_VIDEOS,+ dimensions=("video",),+ metrics=(+ "views",+ "estimatedMinutesWatched",+ "averageViewDuration",+ "averageViewPercentage",+ "likes",+ "dislikes",+ "comments",+ "shares",+ "subscribersGained",+ "subscribersLost",+ ),+ sort="-estimatedMinutesWatched",+ single_page=True,+ ),+ TRAFFIC_SOURCES: YouTubeAnalyticsReportConfig(+ name=TRAFFIC_SOURCES,+ dimensions=("insightTrafficSourceType",),+ metrics=("views", "estimatedMinutesWatched"),+ ),+ PLAYBACK_LOCATIONS: YouTubeAnalyticsReportConfig(+ name=PLAYBACK_LOCATIONS,+ dimensions=("insightPlaybackLocationType",),+ metrics=("views", "estimatedMinutesWatched"),+ ),+ DEVICE_TYPES: YouTubeAnalyticsReportConfig(+ name=DEVICE_TYPES,+ dimensions=("deviceType",),+ metrics=("views", "estimatedMinutesWatched"),+ ),+ OPERATING_SYSTEMS: YouTubeAnalyticsReportConfig(+ name=OPERATING_SYSTEMS,+ dimensions=("operatingSystem",),+ metrics=("views", "estimatedMinutesWatched"),+ ),+ GEOGRAPHY: YouTubeAnalyticsReportConfig(+ name=GEOGRAPHY,+ dimensions=("country",),+ metrics=(+ "views",+ "estimatedMinutesWatched",+ "averageViewDuration",+ "averageViewPercentage",+ "subscribersGained",+ "subscribersLost",+ ),+ ),+ DEMOGRAPHICS: YouTubeAnalyticsReportConfig(+ name=DEMOGRAPHICS,+ dimensions=("ageGroup", "gender"),+ metrics=("viewerPercentage",),+ ),+ SHARING_SERVICES: YouTubeAnalyticsReportConfig(+ name=SHARING_SERVICES,+ dimensions=("sharingService",),+ metrics=("shares",),+ ),+ SUBSCRIBED_STATUS: YouTubeAnalyticsReportConfig(+ name=SUBSCRIBED_STATUS,+ dimensions=("subscribedStatus",),+ metrics=("views", "estimatedMinutesWatched"),+ ),+}++ENDPOINTS = tuple(YOUTUBE_ANALYTICS_REPORTS.keys())++# Every report is filtered server-side by `startDate`/`endDate`, so the day is a real+# incremental cursor for all of them.+DAY_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": DAY_FIELD,+ "type": IncrementalFieldType.DateTime,+ "field": DAY_FIELD,+ "field_type": IncrementalFieldType.DateTime,+ }+]++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = dict.fromkeys(ENDPOINTS, DAY_INCREMENTAL_FIELDS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.pyindex 5cbbe8efeeed..9715d3d9bc60 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/source.py@@ -1,32 +1,285 @@-from typing import cast+from typing import Optional, cast++import requestsfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,+ SourceFieldOauthConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, OauthIntegration++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.integration_accounts import (+ IntegrationAccount,+ IntegrationAccountListingError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.youtubeanalytics import (YouTubeAnalyticsSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (+ DAY_INCREMENTAL_FIELDS,+ REQUIRED_SCOPES,+ REVISION_LOOKBACK_SECONDS,+ YOUTUBE_ANALYTICS_REPORTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.youtube_analytics import (+ YouTubeAnalyticsAuthError,+ YouTubeAnalyticsResumeConfig,+ list_channels,+ validate_credentials as validate_youtube_analytics_credentials,+ youtube_analytics_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+RECONNECT_MESSAGE = (+ "Could not use the credentials for this YouTube Analytics connection. Please reconnect the Google account."+)+@SourceRegistry.register-class YouTubeAnalyticsSource(SimpleSource[YouTubeAnalyticsSourceConfig]):+class YouTubeAnalyticsSource(ResumableSource[YouTubeAnalyticsSourceConfig, YouTubeAnalyticsResumeConfig], OAuthMixin):+ api_docs_url = "https://developers.google.com/youtube/analytics/reference/reports/query"+ supported_versions = ("v2",)+ default_version = "v2"++ lists_tables_without_credentials = True # static report catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.YOUTUBEANALYTICS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": (+ "Google rejected the credentials for this connection. Please reconnect the Google account."+ ),+ "403 Client Error: Forbidden for url: https://youtubeanalytics.googleapis.com": (+ "The connected Google account cannot read this channel's analytics. Reconnect using an "+ "account that manages the channel, and grant the YouTube Analytics permission."+ ),+ "Integration not found": (+ "The Google account for this source is no longer connected. Please reconnect it."+ ),+ # Already the actionable message, so keep it rather than substituting another.+ RECONNECT_MESSAGE: None,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def access_token(self, integration_id: int, team_id: int, force_refresh: bool = False) -> str:+ """A currently valid Google access token for the linked account.++ `force_refresh` re-mints unconditionally, for the mid-sync case where a token that looked+ fresh has already been rejected.+ """+ integration = self.get_oauth_integration(integration_id, team_id)++ oauth = OauthIntegration(integration)+ if force_refresh or oauth.access_token_expired():+ oauth.refresh_access_token()+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED:+ raise YouTubeAnalyticsAuthError(RECONNECT_MESSAGE)++ if not integration.access_token:+ raise YouTubeAnalyticsAuthError(RECONNECT_MESSAGE)++ return integration.access_token++ def get_oauth_accounts(+ self, integration_id: int, team_id: int, search: str | None = None+ ) -> list[IntegrationAccount]:+ # A Google account owns a handful of channels at most, so `search` is ignored here and the+ # endpoint filters the returned list.+ try:+ access_token = self.access_token(integration_id, team_id)+ except ValueError as e:+ raise IntegrationAccountListingError(+ "The Google account for this source is no longer connected. Please reconnect it."+ ) from e+ except YouTubeAnalyticsAuthError as e:+ raise IntegrationAccountListingError(str(e)) from e+ except requests.RequestException as e:+ # `refresh_access_token` only records the failure on the integration when Google answers+ # with a parseable body; a network error or an HTML error page escapes instead.+ raise IntegrationAccountListingError(+ "Could not reach Google to refresh this connection. Please try again in a few minutes."+ ) from e++ try:+ channels = list_channels(access_token)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status in (401, 403):+ raise IntegrationAccountListingError(+ "Google rejected the credentials for this connection. Please reconnect the Google account "+ "and grant access to your YouTube channel."+ ) from e+ if status == 429 or (status is not None and status >= 500):+ raise IntegrationAccountListingError(+ "Google is having trouble responding right now. Please try again in a few minutes."+ ) from e+ # Any other status means we built a bad request, which the user cannot fix.+ raise+ except requests.RequestException as e:+ raise IntegrationAccountListingError(+ "Google is having trouble responding right now. Please try again in a few minutes."+ ) from e++ return [+ IntegrationAccount(+ value=channel["id"],+ display_name=(channel.get("snippet") or {}).get("title") or channel["id"],+ secondary_text=(channel.get("snippet") or {}).get("customUrl"),+ )+ for channel in channels+ if channel.get("id")+ ]++ def get_schemas(+ self,+ config: YouTubeAnalyticsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=report.name,+ supports_incremental=True,+ supports_append=False,+ incremental_fields=DAY_INCREMENTAL_FIELDS,+ # YouTube keeps restating the most recent days, so re-read a trailing window+ # every incremental run instead of freezing a day at its first-imported value.+ default_incremental_lookback_seconds=REVISION_LOOKBACK_SECONDS,+ detected_primary_keys=report.primary_keys,+ )+ for report in YOUTUBE_ANALYTICS_REPORTS.values()+ ]++ if names is not None:+ names_set = set(names)+ schemas = [schema for schema in schemas if schema.name in names_set]++ return schemas++ def validate_credentials(+ self,+ config: YouTubeAnalyticsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if not config.youtube_analytics_integration_id:+ return False, "Connect a Google account to sync YouTube Analytics."++ try:+ access_token = self.access_token(config.youtube_analytics_integration_id, team_id)+ except (ValueError, YouTubeAnalyticsAuthError) as e:+ return False, str(e)+ except requests.RequestException as e:+ return False, f"Could not reach Google to refresh this connection ({e}). Please retry."++ return validate_youtube_analytics_credentials(+ access_token=access_token,+ channel_id=config.channel_id,+ start_date=config.start_date,+ api_version=self.resolve_api_version(api_version),+ )++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[YouTubeAnalyticsResumeConfig]:+ return ResumableSourceManager[YouTubeAnalyticsResumeConfig](inputs, YouTubeAnalyticsResumeConfig)++ def source_for_pipeline(+ self,+ config: YouTubeAnalyticsSourceConfig,+ resumable_source_manager: ResumableSourceManager[YouTubeAnalyticsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ integration_id = config.youtube_analytics_integration_id+ team_id = inputs.team_id++ return youtube_analytics_source(+ access_token=self.access_token(integration_id, team_id),+ refresh_access_token=lambda: self.access_token(integration_id, team_id, force_refresh=True),+ channel_id=config.channel_id,+ start_date=config.start_date,+ endpoint=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.YOU_TUBE_ANALYTICS,category=DataWarehouseSourceCategory.ANALYTICS,label="YouTube Analytics",+ caption=(+ "Pull daily channel metrics from the YouTube Analytics API: views, watch time, subscribers, "+ "traffic sources, geography and demographics.\n\n"+ "Connect the Google account that manages your channel, then pick the channel to sync. PostHog "+ "asks for read-only access to your YouTube Analytics reports and your list of channels."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/youtube-analytics",iconPath="/static/services/youtube_analytics.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ featureFlag="dwh_youtube_analytics",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["youtube", "yt"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldOauthConfig(+ name="youtube_analytics_integration_id",+ label="Google account",+ required=True,+ kind="youtube-analytics",+ requiredScopes=REQUIRED_SCOPES,+ ),+ SourceFieldOauthAccountSelectConfig(+ name="channel_id",+ label="Channel",+ integrationField="youtube_analytics_integration_id",+ integrationKind="youtube-analytics",+ required=True,+ placeholder="Pick a channel the connected account owns",+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="YYYY-MM-DD (defaults to the last 365 days)",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.pynew file mode 100644index 000000000000..9e7b2fabcbc9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics.py@@ -0,0 +1,501 @@+from collections.abc import Iterable+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (+ CHANNEL_DAILY,+ DEMOGRAPHICS,+ GEOGRAPHY,+ MAX_RESULTS_PER_PAGE,+ TOP_VIDEOS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.youtube_analytics import (+ YouTubeAnalyticsClient,+ YouTubeAnalyticsResumeConfig,+ channel_ids_param,+ coerce_day,+ get_rows,+ list_channels,+ resolve_start_day,+ rows_from_result,+ validate_credentials,+ youtube_analytics_source,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.youtube_analytics"+FROZEN_NOW = "2026-07-26"+++class FakeResumeManager(ResumableSourceManager[YouTubeAnalyticsResumeConfig]):+ """In-memory stand-in for the Redis-backed manager."""++ def __init__(self, state: YouTubeAnalyticsResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[YouTubeAnalyticsResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> YouTubeAnalyticsResumeConfig | None:+ return self.state++ def save_state(self, data: YouTubeAnalyticsResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def _response(status: int = 200, json_body: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 300+ response.text = text+ response.json.return_value = json_body if json_body is not None else {}+ response.raise_for_status.side_effect = (+ None if response.ok else requests.HTTPError(f"{status} Client Error", response=response)+ )+ return response+++def _result(headers: list[str], rows: list[list[Any]]) -> dict[str, Any]:+ return {"columnHeaders": [{"name": name} for name in headers], "rows": rows}+++def _run_get_rows(+ endpoint: str,+ query_results: list[dict[str, Any]],+ manager: FakeResumeManager,+ **overrides: Any,+) -> tuple[list[list[dict[str, Any]]], list[dict[str, str]]]:+ """Drive `get_rows` with a stubbed report client, returning yielded batches and sent params."""+ sent: list[dict[str, str]] = []++ def _query(params: dict[str, str]) -> dict[str, Any]:+ sent.append(params)+ return query_results[min(len(sent) - 1, len(query_results) - 1)]++ kwargs: dict[str, Any] = {+ "access_token": "access-token",+ "refresh_access_token": None,+ "channel_id": None,+ "start_date": None,+ "endpoint": endpoint,+ "api_version": "v2",+ "logger": mock.MagicMock(),+ "resumable_source_manager": manager,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ }+ kwargs.update(overrides)++ with mock.patch.object(YouTubeAnalyticsClient, "query", side_effect=_query):+ with mock.patch(f"{MODULE}.make_tracked_session"):+ batches = list(get_rows(**kwargs))++ return batches, sent+++class TestChannelIdsParam:+ @parameterized.expand(+ [+ ("blank", None, "channel==MINE"),+ ("empty_string", "", "channel==MINE"),+ ("whitespace", " ", "channel==MINE"),+ ("explicit", "UC_x5XG1OV2P6uZZ5FSM9Ttw", "channel==UC_x5XG1OV2P6uZZ5FSM9Ttw"),+ ("padded", " UC123 ", "channel==UC123"),+ ]+ )+ def test_builds_ids_filter(self, _name: str, channel_id: str | None, expected: str) -> None:+ assert channel_ids_param(channel_id) == expected+++class TestCoerceDay:+ @parameterized.expand(+ [+ ("iso_string", "2026-07-04", datetime(2026, 7, 4, tzinfo=UTC)),+ ("iso_datetime_string", "2026-07-04T13:00:00+00:00", datetime(2026, 7, 4, tzinfo=UTC)),+ ("date", date(2026, 7, 4), datetime(2026, 7, 4, tzinfo=UTC)),+ ("naive_datetime", datetime(2026, 7, 4, 5, 30), datetime(2026, 7, 4, 5, 30, tzinfo=UTC)),+ ("aware_datetime", datetime(2026, 7, 4, tzinfo=UTC), datetime(2026, 7, 4, tzinfo=UTC)),+ ]+ )+ def test_normalizes_to_utc(self, _name: str, value: Any, expected: datetime) -> None:+ assert coerce_day(value) == expected++ @parameterized.expand([("none", None), ("empty", ""), ("garbage", "not-a-date"), ("number", 20260704)])+ def test_returns_none_for_unusable(self, _name: str, value: Any) -> None:+ assert coerce_day(value) is None+++class TestRowsFromResult:+ def test_zips_column_headers_onto_positional_rows(self) -> None:+ rows = rows_from_result(_result(["day", "views"], [["2026-07-01", 10], ["2026-07-02", 20]]))++ assert rows == [{"day": "2026-07-01", "views": 10}, {"day": "2026-07-02", "views": 20}]++ @parameterized.expand(+ [+ ("no_rows", {"columnHeaders": [{"name": "views"}]}),+ ("no_headers", {"rows": [[1]]}),+ ("empty_body", {}),+ ]+ )+ def test_returns_empty_when_nothing_to_map(self, _name: str, body: dict[str, Any]) -> None:+ assert rows_from_result(body) == []+++class TestYouTubeAnalyticsClient:+ def _client(self, session: mock.MagicMock, **kwargs: Any) -> YouTubeAnalyticsClient:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ return YouTubeAnalyticsClient("tok-1", logger=mock.MagicMock(), **kwargs)++ def test_requests_are_bearer_authorized_with_the_integration_token(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(json_body=_result(["views"], [[1]]))++ self._client(session).query({"ids": "channel==MINE"})++ assert session.get.call_args.kwargs["headers"] == {"Authorization": "Bearer tok-1"}++ def test_rejected_token_is_refreshed_once_and_the_request_retried(self) -> None:+ # A backfill can outlive Google's ~1h access token, so a mid-sync 401 must not fail the job.+ session = mock.MagicMock()+ session.get.side_effect = [_response(status=401), _response(json_body=_result(["views"], [[7]]))]+ refresh = mock.MagicMock(return_value="tok-2")++ body = self._client(session, refresh_access_token=refresh).query({"ids": "channel==MINE"})++ assert rows_from_result(body) == [{"views": 7}]+ assert refresh.call_count == 1+ assert session.get.call_args.kwargs["headers"] == {"Authorization": "Bearer tok-2"}++ def test_a_second_rejection_is_raised_rather_than_refreshed_again(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = [_response(status=401), _response(status=401)]+ refresh = mock.MagicMock(return_value="tok-2")++ with pytest.raises(requests.HTTPError):+ self._client(session, refresh_access_token=refresh).query({"ids": "channel==MINE"})++ assert refresh.call_count == 1++ def test_rejected_token_without_a_refresher_raises(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status=401)++ with pytest.raises(requests.HTTPError):+ self._client(session).query({"ids": "channel==MINE"})++ @parameterized.expand([("forbidden", 403), ("bad_request", 400), ("server_error", 500)])+ def test_failed_report_request_raises(self, _name: str, status: int) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status=status, text="nope")++ with pytest.raises(requests.HTTPError):+ self._client(session).query({"ids": "channel==MINE"})++ def test_reports_url_uses_the_resolved_api_version(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session"):+ client = YouTubeAnalyticsClient("tok", api_version="v3")++ assert client.reports_url == "https://youtubeanalytics.googleapis.com/v3/reports"++ def test_report_bodies_are_kept_out_of_diagnostic_capture(self) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as session_factory:+ YouTubeAnalyticsClient("tok")++ session_factory.assert_called_once_with(capture=False)+++class TestListChannels:+ def _call(self, body: Any) -> tuple[list[dict[str, Any]], mock.MagicMock]:+ session = mock.MagicMock()+ session.get.return_value = _response(json_body=body)+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ return list_channels("tok"), session++ def test_lists_only_the_connected_accounts_own_channels(self) -> None:+ channels, session = self._call({"items": [{"id": "UC123", "snippet": {"title": "Acme"}}]})++ url = session.get.call_args.args[0]+ assert "mine=true" in url+ assert "part=snippet" in url+ assert channels == [{"id": "UC123", "snippet": {"title": "Acme"}}]++ @parameterized.expand([("no_items", {}), ("null_items", {"items": None}), ("empty_items", {"items": []})])+ def test_returns_empty_when_the_account_owns_no_channel(self, _name: str, body: Any) -> None:+ channels, _ = self._call(body)++ assert channels == []++ def test_channel_listings_are_kept_out_of_diagnostic_capture(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(json_body={"items": []})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as session_factory:+ list_channels("tok")++ session_factory.assert_called_once_with(capture=False)+++class TestResolveStartDay:+ @parameterized.expand(+ [+ ("default_lookback", None, False, None, date(2025, 7, 26)),+ ("pinned_start_date", "2026-01-15", False, None, date(2026, 1, 15)),+ ("watermark_wins", "2026-01-15", True, "2026-06-01", date(2026, 6, 1)),+ ("watermark_before_floor_is_clamped", "2026-06-01", True, "2026-01-15", date(2026, 6, 1)),+ ("watermark_ignored_on_full_refresh", "2026-01-15", False, "2026-06-01", date(2026, 1, 15)),+ ("unparseable_watermark_falls_back", "2026-01-15", True, "garbage", date(2026, 1, 15)),+ ("start_before_floor_is_clamped", "2000-01-01", False, None, date(2008, 1, 1)),+ ]+ )+ def test_resolves_first_day(+ self,+ _name: str,+ start_date: str | None,+ should_use_incremental_field: bool,+ last_value: Any,+ expected: date,+ ) -> None:+ assert resolve_start_day(start_date, should_use_incremental_field, last_value, date(2026, 7, 26)) == expected+++@freeze_time(FROZEN_NOW)+class TestGetRows:+ def test_day_dimension_report_covers_a_multi_day_window_per_request(self) -> None:+ manager = FakeResumeManager()+ result = _result(["day", "views"], [["2026-07-20", 5], ["2026-07-21", 6]])++ batches, sent = _run_get_rows(CHANNEL_DAILY, [result], manager, start_date="2026-01-01")++ # 2026-01-01 → 2026-07-25 is three 90-day windows.+ assert [(p["startDate"], p["endDate"]) for p in sent] == [+ ("2026-01-01", "2026-03-31"),+ ("2026-04-01", "2026-06-29"),+ ("2026-06-30", "2026-07-25"),+ ]+ assert sent[0]["dimensions"] == "day"+ assert sent[0]["sort"] == "day"+ # The report's own `day` column is parsed rather than stamped from the window start.+ assert batches[0][0]["day"] == datetime(2026, 7, 20, tzinfo=UTC)++ def test_aggregate_report_is_queried_one_day_at_a_time_and_stamped(self) -> None:+ manager = FakeResumeManager()+ result = _result(["ageGroup", "gender", "viewerPercentage"], [["age18-24", "female", 12.5]])++ batches, sent = _run_get_rows(DEMOGRAPHICS, [result], manager, start_date="2026-07-23")++ assert [(p["startDate"], p["endDate"]) for p in sent] == [+ ("2026-07-23", "2026-07-23"),+ ("2026-07-24", "2026-07-24"),+ ("2026-07-25", "2026-07-25"),+ ]+ assert sent[0]["dimensions"] == "ageGroup,gender"+ assert [batch[0]["day"] for batch in batches] == [+ datetime(2026, 7, 23, tzinfo=UTC),+ datetime(2026, 7, 24, tzinfo=UTC),+ datetime(2026, 7, 25, tzinfo=UTC),+ ]++ def test_stops_before_today_because_the_current_day_is_partial(self) -> None:+ manager = FakeResumeManager()+ _, sent = _run_get_rows(GEOGRAPHY, [_result(["country", "views"], [])], manager, start_date="2026-07-25")++ assert [p["endDate"] for p in sent] == ["2026-07-25"]++ def test_nothing_is_requested_when_the_start_day_is_in_the_future(self) -> None:+ manager = FakeResumeManager()+ batches, sent = _run_get_rows(GEOGRAPHY, [_result(["country"], [])], manager, start_date="2026-08-01")++ assert (batches, sent) == ([], [])++ def test_paginates_a_full_page_with_start_index(self) -> None:+ manager = FakeResumeManager()+ full_page = _result(["country", "views"], [["US", 1]] * MAX_RESULTS_PER_PAGE)+ short_page = _result(["country", "views"], [["FR", 2]])++ batches, sent = _run_get_rows(GEOGRAPHY, [full_page, short_page], manager, start_date="2026-07-25")++ assert [p["startIndex"] for p in sent] == ["1", str(MAX_RESULTS_PER_PAGE + 1)]+ assert len(batches[0]) == MAX_RESULTS_PER_PAGE + 1++ def test_top_n_report_takes_a_single_page(self) -> None:+ manager = FakeResumeManager()+ full_page = _result(["video", "views"], [["vid", 1]] * MAX_RESULTS_PER_PAGE)++ batches, sent = _run_get_rows(TOP_VIDEOS, [full_page], manager, start_date="2026-07-25")++ # YouTube caps `video`-keyed reports at 200 rows, so a full page is the end of the report.+ assert len(sent) == 1+ assert sent[0]["sort"] == "-estimatedMinutesWatched"+ assert len(batches[0]) == MAX_RESULTS_PER_PAGE++ def test_empty_windows_are_not_yielded(self) -> None:+ manager = FakeResumeManager()+ batches, sent = _run_get_rows(GEOGRAPHY, [_result(["country"], [])], manager, start_date="2026-07-23")++ assert batches == []+ assert len(sent) == 3++ def test_saves_resume_state_after_every_window_and_clears_on_completion(self) -> None:+ manager = FakeResumeManager()+ _run_get_rows(GEOGRAPHY, [_result(["country", "views"], [["US", 1]])], manager, start_date="2026-07-24")++ assert [state.next_start_date for state in manager.saved] == ["2026-07-25", "2026-07-26"]+ assert manager.cleared is True++ def test_resumes_from_saved_state_instead_of_the_configured_start(self) -> None:+ manager = FakeResumeManager(YouTubeAnalyticsResumeConfig(next_start_date="2026-07-25"))++ _, sent = _run_get_rows(GEOGRAPHY, [_result(["country"], [])], manager, start_date="2026-01-01")++ assert [p["startDate"] for p in sent] == ["2026-07-25"]++ def test_incremental_watermark_bounds_the_first_window(self) -> None:+ manager = FakeResumeManager()++ _, sent = _run_get_rows(+ GEOGRAPHY,+ [_result(["country"], [])],+ manager,+ start_date="2026-01-01",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 24, tzinfo=UTC),+ )++ assert [p["startDate"] for p in sent] == ["2026-07-24", "2026-07-25"]++ def test_channel_id_is_sent_as_the_ids_filter(self) -> None:+ manager = FakeResumeManager()++ _, sent = _run_get_rows(+ GEOGRAPHY, [_result(["country"], [])], manager, start_date="2026-07-25", channel_id="UC123"+ )++ assert sent[0]["ids"] == "channel==UC123"+++@freeze_time(FROZEN_NOW)+class TestValidateCredentials:+ def _patch_client(self, query: Any) -> Any:+ client = mock.MagicMock(spec=YouTubeAnalyticsClient)+ client.query.side_effect = query+ return mock.patch(f"{MODULE}.YouTubeAnalyticsClient", return_value=client)++ def test_valid_credentials(self) -> None:+ with self._patch_client(query=[{"columnHeaders": [], "rows": []}]):+ assert validate_credentials("access-token", "UC123") == (True, None)++ @parameterized.expand(+ [+ ("unauthorized", 401, "reconnect"),+ ("forbidden", 403, "cannot read this channel"),+ ("bad_channel", 400, "Pick a channel"),+ ("unexpected", 500, "status 500"),+ ]+ )+ def test_report_errors_map_to_actionable_messages(self, _name: str, status: int, fragment: str) -> None:+ error = requests.HTTPError("boom", response=_response(status=status))++ with self._patch_client(query=error):+ is_valid, message = validate_credentials("access-token", "UC123")++ assert is_valid is False+ assert message is not None and fragment in message++ def test_network_failure_is_reported_not_raised(self) -> None:+ with self._patch_client(query=requests.ConnectionError("no route")):+ is_valid, message = validate_credentials("access-token", "UC123")++ assert is_valid is False+ assert message is not None and "Could not reach" in message++ @parameterized.expand(+ [+ ("before_floor", "2000-01-01", "on or after 2008-01-01"),+ ("in_the_future", "2027-01-01", "can't be in the future"),+ ("unparseable", "not-a-date", "Invalid start date"),+ ]+ )+ def test_out_of_range_start_date_is_rejected_before_any_request(+ self, _name: str, start_date: str, fragment: str+ ) -> None:+ # A bad start date is caught before any API call, so no request is made.+ is_valid, message = validate_credentials("access-token", "UC123", start_date=start_date)++ assert is_valid is False+ assert message is not None and fragment in message+++class TestYouTubeAnalyticsSourceResponse:+ @parameterized.expand(+ [+ (CHANNEL_DAILY, ["day"]),+ (TOP_VIDEOS, ["day", "video"]),+ (DEMOGRAPHICS, ["day", "ageGroup", "gender"]),+ ]+ )+ def test_primary_keys_are_unique_table_wide(self, endpoint: str, expected: list[str]) -> None:+ response = youtube_analytics_source(+ access_token="access-token",+ refresh_access_token=None,+ channel_id=None,+ start_date=None,+ endpoint=endpoint,+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.name == endpoint+ assert response.primary_keys == expected++ def test_partitions_and_sorts_on_the_day_column(self) -> None:+ response = youtube_analytics_source(+ access_token="access-token",+ refresh_access_token=None,+ channel_id=None,+ start_date=None,+ endpoint=GEOGRAPHY,+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["day"]+ # Windows are walked oldest-first, so the incremental watermark advances safely.+ assert response.sort_mode == "asc"++ @freeze_time(FROZEN_NOW)+ def test_items_is_lazy_until_iterated(self) -> None:+ manager = FakeResumeManager()+ response = youtube_analytics_source(+ access_token="access-token",+ refresh_access_token=None,+ channel_id=None,+ start_date="2026-07-25",+ endpoint=GEOGRAPHY,+ api_version="v2",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )++ with mock.patch.object(+ YouTubeAnalyticsClient, "query", return_value=_result(["country", "views"], [["US", 3]])+ ):+ with mock.patch(f"{MODULE}.make_tracked_session"):+ batches = list(cast("Iterable[Any]", response.items()))++ assert batches == [[{"country": "US", "views": 3, "day": datetime(2026, 7, 25, tzinfo=UTC)}]]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.pynew file mode 100644index 000000000000..6b271cd05b1f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/tests/test_youtube_analytics_source.py@@ -0,0 +1,381 @@+from types import SimpleNamespace+from typing import Any, cast++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from posthog.schema import (+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldOauthAccountSelectConfig,+ SourceFieldOauthConfig,+)++from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED++from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (+ IntegrationAccountListingError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.youtubeanalytics import (+ YouTubeAnalyticsSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (+ ANALYTICS_SCOPE,+ CHANNEL_DAILY,+ DEMOGRAPHICS,+ ENDPOINTS,+ REVISION_LOOKBACK_SECONDS,+ TOP_VIDEOS,+ YOUTUBE_ANALYTICS_REPORTS,+ YOUTUBE_READONLY_SCOPE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.source import (+ YouTubeAnalyticsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.youtube_analytics import (+ YouTubeAnalyticsAuthError,+ YouTubeAnalyticsResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.source"+INTEGRATION_ID = 42+++def _config(**overrides: Any) -> YouTubeAnalyticsSourceConfig:+ values: dict[str, Any] = {+ "youtube_analytics_integration_id": INTEGRATION_ID,+ "channel_id": "UC123",+ "start_date": None,+ }+ values.update(overrides)+ return YouTubeAnalyticsSourceConfig(**values)+++def _integration(access_token: str | None = "access-token", errors: str = "") -> mock.MagicMock:+ integration = mock.MagicMock()+ integration.access_token = access_token+ integration.errors = errors+ return integration+++def _http_error(status: int) -> requests.HTTPError:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ return requests.HTTPError(f"{status} Client Error", response=response)+++class TestYouTubeAnalyticsSource:+ def setup_method(self) -> None:+ self.source = YouTubeAnalyticsSource()+ self.team_id = 123+ self.config = _config()++ def _patch_integration(self, integration: mock.MagicMock, expired: bool = False) -> Any:+ """Stand in for the DB-backed integration and its OAuth refresh."""+ oauth = mock.MagicMock()+ oauth.access_token_expired.return_value = expired+ return (+ mock.patch.object(YouTubeAnalyticsSource, "get_oauth_integration", return_value=integration),+ mock.patch(f"{MODULE}.OauthIntegration", return_value=oauth),+ oauth,+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.YOUTUBEANALYTICS++ def test_source_config_is_released_as_alpha(self) -> None:+ config = self.source.get_source_config++ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ # Dropping the flag would expose the source to every project, not just the ones opted in.+ assert config.featureFlag == "dwh_youtube_analytics"+ assert config.iconPath == "/static/services/youtube_analytics.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/youtube-analytics"++ def test_authentication_is_a_posthog_owned_oauth_app(self) -> None:+ fields = self.source.get_source_config.fields+ oauth = next(f for f in fields if isinstance(f, SourceFieldOauthConfig))++ assert oauth.name == "youtube_analytics_integration_id"+ assert oauth.kind == "youtube-analytics"+ assert oauth.required is True+ # The frontend warns on a missing grant, so both scopes the source calls must be listed.+ assert oauth.requiredScopes is not None+ assert set(oauth.requiredScopes.split()) == {ANALYTICS_SCOPE, YOUTUBE_READONLY_SCOPE}++ def test_no_field_asks_the_user_for_oauth_credentials(self) -> None:+ # Users must never be asked to register their own Google app and paste a refresh token.+ inputs = [f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)]++ assert [f.name for f in inputs] == ["start_date"]+ assert inputs[0].type == SourceFieldInputConfigType.TEXT+ assert inputs[0].required is False++ def test_channel_is_picked_from_the_connected_account(self) -> None:+ fields = self.source.get_source_config.fields+ channel = next(f for f in fields if isinstance(f, SourceFieldOauthAccountSelectConfig))++ assert channel.name == "channel_id"+ assert channel.required is True+ assert channel.integrationField == "youtube_analytics_integration_id"+ assert channel.integrationKind == "youtube-analytics"++ def test_pins_the_vendor_api_version_it_calls(self) -> None:+ assert self.source.supported_versions == ("v2",)+ assert self.source.default_version == "v2"+ assert (self.source.api_docs_url or "").startswith("https://")++ def test_get_schemas_returns_every_report(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_every_report_is_incremental_on_day(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)++ assert schema.supports_incremental is True+ assert schema.supports_append is False+ assert [field["field"] for field in schema.incremental_fields] == ["day"]+ # YouTube restates recent days, so incremental runs must re-read a trailing window.+ assert schema.default_incremental_lookback_seconds == REVISION_LOOKBACK_SECONDS++ @parameterized.expand(+ [+ (CHANNEL_DAILY, ["day"]),+ (TOP_VIDEOS, ["day", "video"]),+ (DEMOGRAPHICS, ["day", "ageGroup", "gender"]),+ ]+ )+ def test_primary_keys_include_every_breakdown_dimension(self, endpoint: str, expected: list[str]) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.detected_primary_keys == expected++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=[TOP_VIDEOS])+ assert [schema.name for schema in schemas] == [TOP_VIDEOS]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_lists_tables_without_credentials(self) -> None:+ # The report catalog is static, so public docs can render it without connecting.+ assert self.source.lists_tables_without_credentials is True++ def test_canonical_descriptions_cover_every_report(self) -> None:+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)+ for endpoint, entry in descriptions.items():+ columns = entry.get("columns") or {}+ expected_columns = {"day", *YOUTUBE_ANALYTICS_REPORTS[endpoint].dimensions}+ assert expected_columns <= set(columns)++ @parameterized.expand(+ [+ ("401 Client Error",),+ ("403 Client Error: Forbidden for url: https://youtubeanalytics.googleapis.com",),+ ("Integration not found",),+ ]+ )+ def test_auth_failures_are_non_retryable(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ @parameterized.expand(+ [+ ("fresh_token_is_reused", False, False, 0),+ ("stale_token_is_refreshed", True, False, 1),+ ("forced_refresh_always_mints", False, True, 1),+ ]+ )+ def test_access_token_refreshes_only_when_needed(+ self, _name: str, expired: bool, force_refresh: bool, refresh_calls: int+ ) -> None:+ get_integration, oauth_cls, oauth = self._patch_integration(_integration(), expired=expired)++ with get_integration, oauth_cls:+ token = self.source.access_token(INTEGRATION_ID, self.team_id, force_refresh=force_refresh)++ assert token == "access-token"+ assert oauth.refresh_access_token.call_count == refresh_calls++ @parameterized.expand(+ [+ ("refresh_failed", "access-token", ERROR_TOKEN_REFRESH_FAILED),+ ("no_token_stored", None, ""),+ ]+ )+ def test_unusable_credentials_raise_instead_of_syncing_with_no_token(+ self, _name: str, access_token: str | None, errors: str+ ) -> None:+ get_integration, oauth_cls, _ = self._patch_integration(+ _integration(access_token=access_token, errors=errors), expired=True+ )++ with get_integration, oauth_cls, pytest.raises(YouTubeAnalyticsAuthError):+ self.source.access_token(INTEGRATION_ID, self.team_id)++ def test_get_oauth_accounts_lists_the_connected_accounts_channels(self) -> None:+ get_integration, oauth_cls, _ = self._patch_integration(_integration())+ channels = [+ {"id": "UC123", "snippet": {"title": "Acme", "customUrl": "@acme"}},+ {"id": "UC456", "snippet": {}},+ ]++ with get_integration, oauth_cls, mock.patch(f"{MODULE}.list_channels", return_value=channels):+ accounts = self.source.get_oauth_accounts(INTEGRATION_ID, self.team_id)++ assert [(a.value, a.display_name, a.secondary_text) for a in accounts] == [+ ("UC123", "Acme", "@acme"),+ ("UC456", "UC456", None),+ ]++ @parameterized.expand(+ [+ ("unauthorized", 401, "reconnect"),+ ("forbidden", 403, "reconnect"),+ ("rate_limited", 429, "try again"),+ ("server_error", 503, "try again"),+ ]+ )+ def test_get_oauth_accounts_surfaces_actionable_listing_failures(+ self, _name: str, status: int, fragment: str+ ) -> None:+ get_integration, oauth_cls, _ = self._patch_integration(_integration())++ with (+ get_integration,+ oauth_cls,+ mock.patch(f"{MODULE}.list_channels", side_effect=_http_error(status)),+ pytest.raises(IntegrationAccountListingError) as error,+ ):+ self.source.get_oauth_accounts(INTEGRATION_ID, self.team_id)++ assert fragment in str(error.value).lower()++ def test_get_oauth_accounts_on_a_deleted_integration_asks_for_a_reconnect(self) -> None:+ with (+ mock.patch.object(+ YouTubeAnalyticsSource, "get_oauth_integration", side_effect=ValueError("Integration not found: 42")+ ),+ pytest.raises(IntegrationAccountListingError),+ ):+ self.source.get_oauth_accounts(INTEGRATION_ID, self.team_id)++ def test_validate_credentials_without_an_integration(self) -> None:+ is_valid, error = self.source.validate_credentials(_config(youtube_analytics_integration_id=0), self.team_id)++ assert is_valid is False+ assert error is not None and "Connect a Google account" in error++ @parameterized.expand(+ [+ ("valid", (True, None), True, None),+ ("rejected", (False, "Google rejected the connected account's credentials."), False, "Google rejected"),+ ]+ )+ def test_validate_credentials_probes_with_the_integration_token(+ self, _name: str, mock_return: tuple[bool, str | None], expected_valid: bool, expected_fragment: str | None+ ) -> None:+ get_integration, oauth_cls, _ = self._patch_integration(_integration())++ with get_integration, oauth_cls, mock.patch(f"{MODULE}.validate_youtube_analytics_credentials") as validate:+ validate.return_value = mock_return+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ if expected_fragment is None:+ assert error is None+ else:+ assert error is not None and expected_fragment in error+ validate.assert_called_once_with(+ access_token="access-token", channel_id="UC123", start_date=None, api_version="v2"+ )++ def test_validate_credentials_reports_an_unusable_connection(self) -> None:+ get_integration, oauth_cls, _ = self._patch_integration(_integration(access_token=None), expired=True)++ with get_integration, oauth_cls:+ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error is not None and "reconnect" in error.lower()++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is YouTubeAnalyticsResumeConfig++ def _inputs(self, **overrides: Any) -> SourceInputs:+ values: dict[str, Any] = {+ "schema_name": CHANNEL_DAILY,+ "team_id": self.team_id,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "api_version": None,+ "should_use_incremental_field": True,+ "incremental_field": "day",+ "db_incremental_field_last_value": "2026-07-01",+ }+ values.update(overrides)+ return cast(SourceInputs, SimpleNamespace(**values))++ def test_source_for_pipeline_syncs_with_the_integration_token(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ inputs = self._inputs()+ get_integration, oauth_cls, _ = self._patch_integration(_integration())++ with get_integration, oauth_cls, mock.patch(f"{MODULE}.youtube_analytics_source") as mock_source:+ response = self.source.source_for_pipeline(_config(start_date="2026-01-01"), manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["access_token"] == "access-token"+ assert kwargs["channel_id"] == "UC123"+ assert kwargs["start_date"] == "2026-01-01"+ assert kwargs["endpoint"] == CHANNEL_DAILY+ assert kwargs["api_version"] == "v2"+ assert kwargs["logger"] is inputs.logger+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-07-01"+ assert response is mock_source.return_value++ def test_source_for_pipeline_hands_the_sync_a_forced_token_refresh(self) -> None:+ # Google tokens expire mid-backfill, so the sync must be able to re-mint one.+ manager = mock.MagicMock(spec=ResumableSourceManager)+ get_integration, oauth_cls, oauth = self._patch_integration(_integration())++ with get_integration, oauth_cls, mock.patch(f"{MODULE}.youtube_analytics_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, self._inputs())+ assert oauth.refresh_access_token.call_count == 0++ assert mock_source.call_args.kwargs["refresh_access_token"]() == "access-token"+ assert oauth.refresh_access_token.call_count == 1++ def test_source_for_pipeline_drops_watermark_on_full_refresh(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ get_integration, oauth_cls, _ = self._patch_integration(_integration())++ with get_integration, oauth_cls, mock.patch(f"{MODULE}.youtube_analytics_source") as mock_source:+ self.source.source_for_pipeline(+ self.config, manager, self._inputs(schema_name=TOP_VIDEOS, should_use_incremental_field=False)+ )++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_honors_a_pinned_api_version(self) -> None:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ get_integration, oauth_cls, _ = self._patch_integration(_integration())++ with get_integration, oauth_cls, mock.patch(f"{MODULE}.youtube_analytics_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, self._inputs(api_version="v3"))++ assert mock_source.call_args.kwargs["api_version"] == "v3"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.pynew file mode 100644index 000000000000..aa8da01042a2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/youtube_analytics/youtube_analytics.py@@ -0,0 +1,341 @@+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.youtube_analytics.settings import (+ DATA_LATENCY_DAYS,+ DAY_DIMENSION_WINDOW_DAYS,+ DAY_FIELD,+ DEFAULT_LOOKBACK_DAYS,+ MAX_CHANNELS_PER_PAGE,+ MAX_RESULTS_PER_PAGE,+ MIN_START_DATE,+ YOUTUBE_ANALYTICS_HOST,+ YOUTUBE_ANALYTICS_REPORTS,+ YOUTUBE_DATA_HOST,+ YouTubeAnalyticsReportConfig,+)++REQUEST_TIMEOUT_SECONDS = 120+DEFAULT_API_VERSION = "v2"++# Called to mint a fresh access token when the current one is rejected mid-sync.+AccessTokenRefresher = Callable[[], str]+++@frozen+class YouTubeAnalyticsResumeConfig:+ # ISO date (YYYY-MM-DD) of the next day-window to request.+ next_start_date: str+++class YouTubeAnalyticsAuthError(Exception):+ """The connected Google account's credentials were rejected or could not be refreshed."""+++def channel_ids_param(channel_id: str | None) -> str:+ """The `ids` filter for `reports.query` — the authorized channel unless one is pinned."""+ cleaned = (channel_id or "").strip()+ return f"channel=={cleaned}" if cleaned else "channel==MINE"+++def coerce_day(value: Any) -> Optional[datetime]:+ """Normalize a YouTube `day` value (or a stored watermark) to a UTC midnight datetime."""+ if isinstance(value, datetime):+ return value if value.tzinfo else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime(value.year, value.month, value.day, tzinfo=UTC)+ if isinstance(value, str) and value:+ try:+ return datetime.strptime(value[:10], "%Y-%m-%d").replace(tzinfo=UTC)+ except ValueError:+ return None+ return None+++def rows_from_result(body: dict[str, Any]) -> list[dict[str, Any]]:+ """Zip `reports.query`'s positional rows against its `columnHeaders` into dicts."""+ headers = [header.get("name") for header in body.get("columnHeaders") or []]+ if not headers:+ return []+ return [dict(zip(headers, row)) for row in body.get("rows") or []]+++class YouTubeAnalyticsClient:+ """Queries `reports.query` with the connected Google account's access token."""++ def __init__(+ self,+ access_token: str,+ refresh_access_token: AccessTokenRefresher | None = None,+ api_version: str = DEFAULT_API_VERSION,+ logger: FilteringBoundLogger | None = None,+ ) -> None:+ self._token = access_token+ self._refresh_access_token = refresh_access_token+ self._api_version = api_version+ self._logger = logger+ # The token rides the `Authorization` header, which the tracked transport already scrubs.+ # capture=False: report bodies are positional rows (top videos, geography, demographics,+ # engagement) with no field names for the scrubber to match on, so they stay out of+ # diagnostic HTTP samples entirely. Requests are still metered and logged.+ self._session = make_tracked_session(capture=False)++ @property+ def reports_url(self) -> str:+ return f"{YOUTUBE_ANALYTICS_HOST}/{self._api_version}/reports"++ def query(self, params: dict[str, str]) -> dict[str, Any]:+ url = f"{self.reports_url}?{urlencode(params)}"++ def _get(token: str) -> requests.Response:+ return self._session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ response = _get(self._token)+ # Google access tokens last ~1h; a long backfill can outlive one, so refresh once on 401.+ if response.status_code == 401 and self._refresh_access_token is not None:+ self._token = self._refresh_access_token()+ response = _get(self._token)++ if not response.ok:+ if self._logger is not None:+ self._logger.error(+ f"YouTube Analytics API error: status={response.status_code}, body={response.text[:500]}"+ )+ response.raise_for_status()++ return response.json()+++def min_start_day() -> date:+ return datetime.strptime(MIN_START_DATE, "%Y-%m-%d").date()+++def validate_start_date(start_date: str | None) -> tuple[bool, Optional[str]]:+ """Reject a pinned start date that predates YouTube Analytics data or sits in the future — an+ unbounded historical range fans out into one request per day per report."""+ if not start_date:+ return True, None+ parsed = coerce_day(start_date)+ if parsed is None:+ return False, f"Invalid start date '{start_date}'. Use the format YYYY-MM-DD."+ if parsed.date() < min_start_day():+ return False, f"Start date must be on or after {MIN_START_DATE}."+ if parsed.date() > datetime.now(UTC).date():+ return False, "Start date can't be in the future."+ return True, None+++def list_channels(access_token: str) -> list[dict[str, Any]]:+ """Channels the connected Google account owns, so the user picks one instead of hunting for its ID."""+ # capture=False: the channel list carries customer-owned channel titles and descriptions, so it+ # stays out of diagnostic HTTP samples for the same reason report bodies do.+ session = make_tracked_session(capture=False)+ params = {"part": "snippet", "mine": "true", "maxResults": str(MAX_CHANNELS_PER_PAGE)}+ response = session.get(+ f"{YOUTUBE_DATA_HOST}/channels?{urlencode(params)}",+ headers={"Authorization": f"Bearer {access_token}"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return response.json().get("items") or []+++def validate_credentials(+ access_token: str,+ channel_id: str | None = None,+ start_date: str | None = None,+ api_version: str = DEFAULT_API_VERSION,+) -> tuple[bool, Optional[str]]:+ ok, message = validate_start_date(start_date)+ if not ok:+ return False, message++ client = YouTubeAnalyticsClient(access_token, api_version=api_version)++ yesterday = (datetime.now(UTC) - timedelta(days=DATA_LATENCY_DAYS)).date()+ try:+ client.query(+ {+ "ids": channel_ids_param(channel_id),+ "startDate": yesterday.isoformat(),+ "endDate": yesterday.isoformat(),+ "metrics": "views",+ "maxResults": "1",+ }+ )+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status == 401:+ return False, "Google rejected the connected account's credentials. Please reconnect the integration."+ if status == 403:+ return (+ False,+ "The connected Google account cannot read this channel's analytics. Reconnect using an "+ "account that manages the channel, and grant the YouTube Analytics permission.",+ )+ if status == 400:+ return False, "YouTube rejected the channel. Pick a channel the connected account owns."+ return False, f"Unexpected response from the YouTube Analytics API (status {status})."+ except Exception as e:+ return False, f"Could not reach the YouTube Analytics API ({e}). Please retry."++ return True, None+++def resolve_start_day(+ start_date: str | None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ today: date,+) -> date:+ """Earliest day to request: the stored watermark when syncing incrementally, else the+ user's pinned start date, else a bounded first-sync horizon."""+ configured = coerce_day(start_date)+ # Clamp to the supported floor so a start date saved before that guard existed still can't+ # walk the range back before YouTube has data.+ floor = max(+ configured.date() if configured else today - timedelta(days=DEFAULT_LOOKBACK_DAYS),+ min_start_day(),+ )++ if should_use_incremental_field:+ watermark = coerce_day(db_incremental_field_last_value)+ if watermark is not None:+ return max(floor, watermark.date())++ return floor+++def _fetch_window(+ client: YouTubeAnalyticsClient,+ report: YouTubeAnalyticsReportConfig,+ ids: str,+ window_start: date,+ window_end: date,+) -> list[dict[str, Any]]:+ dimensions = ((DAY_FIELD,) if report.day_is_dimension else ()) + report.dimensions+ stamped_day = coerce_day(window_start)+ collected: list[dict[str, Any]] = []+ start_index = 1++ while True:+ params = {+ "ids": ids,+ "startDate": window_start.isoformat(),+ "endDate": window_end.isoformat(),+ "metrics": ",".join(report.metrics),+ "maxResults": str(MAX_RESULTS_PER_PAGE),+ "startIndex": str(start_index),+ }+ if dimensions:+ params["dimensions"] = ",".join(dimensions)+ if report.sort:+ params["sort"] = report.sort++ rows = rows_from_result(client.query(params))+ for row in rows:+ row[DAY_FIELD] = coerce_day(row.get(DAY_FIELD)) if report.day_is_dimension else stamped_day+ collected.extend(rows)++ if report.single_page or len(rows) < MAX_RESULTS_PER_PAGE:+ break+ start_index += len(rows)++ return collected+++def get_rows(+ access_token: str,+ refresh_access_token: AccessTokenRefresher | None,+ channel_id: str | None,+ start_date: str | None,+ endpoint: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[YouTubeAnalyticsResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ report = YOUTUBE_ANALYTICS_REPORTS[endpoint]+ client = YouTubeAnalyticsClient(+ access_token, refresh_access_token=refresh_access_token, api_version=api_version, logger=logger+ )+ ids = channel_ids_param(channel_id)++ today = datetime.now(UTC).date()+ # Today is always partial and YouTube keeps revising the last couple of days, so stop short.+ end_day = today - timedelta(days=DATA_LATENCY_DAYS)+ cursor = resolve_start_day(start_date, should_use_incremental_field, db_incremental_field_last_value, today)++ # A persisted resume cursor wins so a heartbeat-timed-out activity picks up where it stopped.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ resumed = coerce_day(resume.next_start_date)+ if resumed is not None:+ cursor = resumed.date()+ logger.debug(f"YouTube Analytics: resuming {endpoint} from {cursor.isoformat()}")++ while cursor <= end_day:+ if report.day_is_dimension:+ window_end = min(cursor + timedelta(days=DAY_DIMENSION_WINDOW_DAYS - 1), end_day)+ else:+ window_end = cursor++ rows = _fetch_window(client, report, ids, cursor, window_end)+ if rows:+ yield rows++ cursor = window_end + timedelta(days=1)+ # Saved after the window is yielded: a crash re-yields the last window and the merge+ # on the day-keyed primary key dedupes it, rather than silently skipping days.+ resumable_source_manager.save_state(YouTubeAnalyticsResumeConfig(next_start_date=cursor.isoformat()))++ resumable_source_manager.clear_state()+++def youtube_analytics_source(+ access_token: str,+ refresh_access_token: AccessTokenRefresher | None,+ channel_id: str | None,+ start_date: str | None,+ endpoint: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[YouTubeAnalyticsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ report = YOUTUBE_ANALYTICS_REPORTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ refresh_access_token=refresh_access_token,+ channel_id=channel_id,+ start_date=start_date,+ endpoint=endpoint,+ api_version=api_version,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=report.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[DAY_FIELD],+ sort_mode="asc",+ )diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b135d64e6856..77b8453fa25a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -6284,6 +6284,7 @@ export namespace Schemas {AwsS3: 'aws-s3',S3Compatible: 's3-compatible',Snowflake: 'snowflake',+ YoutubeAnalytics: 'youtube-analytics',} as const;export interface ErrorTrackingExternalReferenceIntegration {@@ -42489,6 +42490,7 @@ export namespace Schemas {* * `tiktok-ads` - Tiktok Ads* * `twilio` - Twilio* * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics*/export type IntegrationKindEnum = typeof IntegrationKindEnum[keyof typeof IntegrationKindEnum];@@ -42540,6 +42542,7 @@ export namespace Schemas {TiktokAds: 'tiktok-ads',Twilio: 'twilio',Vercel: 'vercel',+ YoutubeAnalytics: 'youtube-analytics',} as const;export interface IntegrationAccessRequest {@@ -42590,7 +42593,8 @@ export namespace Schemas {* * `stripe` - Stripe* * `tiktok-ads` - Tiktok Ads* * `twilio` - Twilio- * * `vercel` - Vercel */+ * * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics */kind: IntegrationKindEnum;/*** Explanation from the requester of why this integration is needed. Shown to admins in the notification email.@@ -88430,6 +88434,7 @@ export namespace Schemas {* * `tiktok-ads` - Tiktok Ads* * `twilio` - Twilio* * `vercel` - Vercel+ * * `youtube-analytics` - Youtube Analytics*/kind?: IntegrationsListKind;/**@@ -88492,6 +88497,7 @@ export namespace Schemas {TiktokAds: 'tiktok-ads',Twilio: 'twilio',Vercel: 'vercel',+ YoutubeAnalytics: 'youtube-analytics',} as const;export type IntegrationsChannelsRetrieveParams = {diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.tsindex 342bb30f206b..a74647a39153 100644--- a/services/mcp/src/generated/integrations/api.ts+++ b/services/mcp/src/generated/integrations/api.ts@@ -65,10 +65,11 @@ export const IntegrationsListQueryParams = /* @__PURE__ */ zod.object({'tiktok-ads','twilio','vercel',+ 'youtube-analytics',]).optional().describe(- '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel'+ '\* `anthropic` - Anthropic\n\* `apns` - Apple Push\n\* `aws-redshift` - Aws Redshift\n\* `aws-s3` - Aws S3\n\* `azure-blob` - Azure Blob\n\* `bing-ads` - Bing Ads\n\* `clickup` - Clickup\n\* `customerio-app` - Customerio App\n\* `customerio-track` - Customerio Track\n\* `customerio-webhook` - Customerio Webhook\n\* `databricks` - Databricks\n\* `email` - Email\n\* `firebase` - Firebase\n\* `github` - Github\n\* `gitlab` - Gitlab\n\* `google-ads` - Google Ads\n\* `google-analytics` - Google Analytics\n\* `google-calendar` - Google Calendar\n\* `google-cloud-service-account` - Google Cloud Service Account\n\* `google-cloud-storage` - Google Cloud Storage\n\* `google-pubsub` - Google Pubsub\n\* `google-search-console` - Google Search Console\n\* `google-sheets` - Google Sheets\n\* `hubspot` - Hubspot\n\* `instagram` - Instagram\n\* `intercom` - Intercom\n\* `jira` - Jira\n\* `linear` - Linear\n\* `linkedin-ads` - Linkedin Ads\n\* `meta-ads` - Meta Ads\n\* `pardot` - Pardot\n\* `pinterest-ads` - Pinterest Ads\n\* `postgresql` - Postgresql\n\* `posthog` - Posthog\n\* `reddit-ads` - Reddit Ads\n\* `resend` - Resend\n\* `s3-compatible` - S3 Compatible\n\* `salesforce` - Salesforce\n\* `slack` - Slack\n\* `slack-posthog-code` - Slack Posthog Code\n\* `snapchat` - Snapchat\n\* `snowflake` - Snowflake\n\* `stripe` - Stripe\n\* `tiktok-ads` - Tiktok Ads\n\* `twilio` - Twilio\n\* `vercel` - Vercel\n\* `youtube-analytics` - Youtube Analytics'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.jsonindex 21c6dad5f3b5..36f78b38b6eb 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-list.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"kind": {- "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel",+ "description": "* `anthropic` - Anthropic\n* `apns` - Apple Push\n* `aws-redshift` - Aws Redshift\n* `aws-s3` - Aws S3\n* `azure-blob` - Azure Blob\n* `bing-ads` - Bing Ads\n* `clickup` - Clickup\n* `customerio-app` - Customerio App\n* `customerio-track` - Customerio Track\n* `customerio-webhook` - Customerio Webhook\n* `databricks` - Databricks\n* `email` - Email\n* `firebase` - Firebase\n* `github` - Github\n* `gitlab` - Gitlab\n* `google-ads` - Google Ads\n* `google-analytics` - Google Analytics\n* `google-calendar` - Google Calendar\n* `google-cloud-service-account` - Google Cloud Service Account\n* `google-cloud-storage` - Google Cloud Storage\n* `google-pubsub` - Google Pubsub\n* `google-search-console` - Google Search Console\n* `google-sheets` - Google Sheets\n* `hubspot` - Hubspot\n* `instagram` - Instagram\n* `intercom` - Intercom\n* `jira` - Jira\n* `linear` - Linear\n* `linkedin-ads` - Linkedin Ads\n* `meta-ads` - Meta Ads\n* `pardot` - Pardot\n* `pinterest-ads` - Pinterest Ads\n* `postgresql` - Postgresql\n* `posthog` - Posthog\n* `reddit-ads` - Reddit Ads\n* `resend` - Resend\n* `s3-compatible` - S3 Compatible\n* `salesforce` - Salesforce\n* `slack` - Slack\n* `slack-posthog-code` - Slack Posthog Code\n* `snapchat` - Snapchat\n* `snowflake` - Snowflake\n* `stripe` - Stripe\n* `tiktok-ads` - Tiktok Ads\n* `twilio` - Twilio\n* `vercel` - Vercel\n* `youtube-analytics` - Youtube Analytics","enum": ["anthropic","apns",@@ -49,7 +49,8 @@"stripe","tiktok-ads","twilio",- "vercel"+ "vercel",+ "youtube-analytics"],"type": "string"},