: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): add the Twitter (X) source (#111861)
Tom Owers248176dac64d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 38dfb75f2659..c00253c213cf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -783,6 +783,7 @@ the row lists both.| twelve_labs | HTTP | requests | ✅ || twenty | HTTP | requests + `rest_source.RESTClient` | ✅ || twilio | HTTP | requests | ✅ |+| twitter | HTTP | requests + `rest_source.RESTClient` | ✅ || twitter_ads | HTTP | requests | ✅ || tyntec_sms | HTTP | requests + `rest_source.RESTClient` | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1462,7 +1463,6 @@ doesn't conflict with concurrent PRs.- triple_whale- trustradius- twitch- two_c2p- tyntec_sms- typesensediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 5025e607cc8e..44657dd5486c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -215,6 +215,10 @@ _RATE_LIMIT_RESET_HEADERS: tuple[tuple[str, Callable[[str], Optional[float]]], .# Sentry signals its rate-limit window with a UNIX epoch timestamp rather than ``Retry-After``,# and Sentry's flat / fan-out endpoints (e.g. ``project_users``) sync through this client too.("X-Sentry-Rate-Limit-Reset", _seconds_from_epoch_reset),+ # X (Twitter) answers 429 with this UNIX epoch reset and no ``Retry-After``. Its windows are 15+ # minutes wide and some endpoints allow only a handful of requests per window, so a backfill+ # that falls back to exponential backoff spends its whole attempt budget inside one window.+ ("x-rate-limit-reset", _seconds_from_epoch_reset),# The common ``X-RateLimit-*`` convention, spelled with a UNIX epoch reset and no# ``Retry-After`` — SendGrid answers every 429 this way, and its Email Activity endpoint is# capped at 6 requests/minute, so without honoring the reset a message-activity backfilldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.pyindex 6ffba7a6646a..2dcc380ea3d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py@@ -772,6 +772,18 @@ class TestRESTClient:assert _parse_retry_after(response) == expected+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.datetime")+ def test_parse_retry_after_honors_x_rate_limit_reset(self, mock_datetime) -> None:+ # X answers 429 with a UNIX epoch reset and no ``Retry-After``. Its windows run 15 minutes,+ # so without this the exponential fallback burns the attempt budget inside one window.+ now = datetime(2026, 3, 6, 12, 0, 0, tzinfo=UTC)+ mock_datetime.now.return_value = now++ response = _make_response({"title": "Too Many Requests"}, status_code=429)+ response.headers["x-rate-limit-reset"] = str(int(now.timestamp()) + 120)++ assert _parse_retry_after(response) == 120+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.datetime")def test_parse_retry_after_caps_sentry_reset_header(self, mock_datetime) -> None:# A reset far in the future must be clamped to MAX_RETRY_AFTER_SECONDS.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitter.pyindex 1f308089445c..5dd208a7fcc4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/twitter.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass TwitterSourceConfig(config.Config):- pass+ bearer_token: str+ username: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/canonical_descriptions.pynew file mode 100644index 000000000000..b8e0aac9d766--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/canonical_descriptions.py@@ -0,0 +1,93 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_POST_COLUMNS = {+ "id": "Unique identifier of the post.",+ "text": "The content of the post.",+ "created_at": "Creation time of the post.",+ "author_id": "Unique identifier of the user who posted it.",+ "conversation_id": "The post ID of the original post in the conversation this post belongs to.",+ "in_reply_to_user_id": "If the post is a reply, the user ID of the account the reply answers.",+ "referenced_tweets": "A list of posts this post refers to, with the type of reference (replied_to, quoted, retweeted).",+ "public_metrics": "Engagement counts anyone can see: retweet_count, reply_count, like_count, quote_count, bookmark_count and impression_count.",+ "lang": "Language of the post, as a BCP47 tag detected by X.",+ "entities": "Entities X parsed out of the text: hashtags, cashtags, mentions, URLs and annotations.",+ "attachments": "Media keys and poll IDs for the media and polls attached to the post.",+ "geo": "Place ID and coordinates attached to the post.",+ "possibly_sensitive": "Whether the content may be recognized as sensitive.",+ "reply_settings": "Who can reply to the post: everyone, mentionedUsers or followers.",+ "edit_controls": "When the post's edit window closes, how many edits remain, and whether it is still editable.",+ "edit_history_tweet_ids": "Post IDs of every version of this post, oldest first.",+ "note_tweet": "The full text and entities of a long-form post, which `text` truncates.",+ "withheld": "Countries the post is withheld in, and the reason.",+}++_USER_COLUMNS = {+ "id": "Unique identifier of the account.",+ "username": "The account's handle, without the leading @.",+ "name": "The account's display name.",+ "created_at": "Creation time of the account.",+ "description": "The account's bio text.",+ "entities": "URLs, hashtags, cashtags and mentions parsed out of the bio and the profile URL.",+ "location": "The location the account reports in its profile. Free text, not validated.",+ "most_recent_tweet_id": "Post ID of the account's most recent post.",+ "pinned_tweet_id": "Post ID of the post pinned to the account's profile.",+ "profile_image_url": "URL of the account's profile image.",+ "protected": "Whether the account's posts are visible only to its followers.",+ "public_metrics": "Audience counts anyone can see: followers_count, following_count, tweet_count, listed_count and like_count.",+ "url": "The URL in the account's profile.",+ "verified": "Whether the account is verified.",+ "verified_type": "The kind of verification on the account: blue, business, government or none.",+ "withheld": "Countries the account is withheld in, and the reason.",+}++_DOCS_POSTS = "https://docs.x.com/x-api/posts/user-posts-timeline-by-user-id"+_DOCS_USERS = "https://docs.x.com/x-api/users/user-lookup-by-usernames"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Profile": {+ "description": "The public profile of the X account this source is connected to, one row per sync.",+ "docs_url": _DOCS_USERS,+ "columns": _USER_COLUMNS,+ },+ "Posts": {+ "description": "Posts composed by the connected account, including replies and reposts.",+ "docs_url": _DOCS_POSTS,+ "columns": _POST_COLUMNS,+ },+ "Mentions": {+ "description": "Posts by other accounts that mention the connected account.",+ "docs_url": "https://docs.x.com/x-api/posts/user-mention-timeline-by-user-id",+ "columns": _POST_COLUMNS,+ },+ "LikedPosts": {+ "description": "Posts the connected account has liked.",+ "docs_url": "https://docs.x.com/x-api/users/get-liked-posts",+ "columns": _POST_COLUMNS,+ },+ "Followers": {+ "description": "Accounts that follow the connected account, one row per follower.",+ "docs_url": "https://docs.x.com/x-api/users/followers-by-user-id",+ "columns": _USER_COLUMNS,+ },+ "Following": {+ "description": "Accounts the connected account follows, one row per followed account.",+ "docs_url": "https://docs.x.com/x-api/users/following-by-user-id",+ "columns": _USER_COLUMNS,+ },+ "OwnedLists": {+ "description": "Lists owned by the connected account.",+ "docs_url": "https://docs.x.com/x-api/users/get-owned-lists",+ "columns": {+ "id": "Unique identifier of the list.",+ "name": "The name of the list.",+ "created_at": "Creation time of the list.",+ "description": "A short description of the list.",+ "follower_count": "Number of accounts following the list.",+ "member_count": "Number of accounts on the list.",+ "owner_id": "Unique identifier of the account that owns the list.",+ "private": "Whether the list is visible only to its owner.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/settings.pynew file mode 100644index 000000000000..51a57b538b79--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/settings.py@@ -0,0 +1,157 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.x.com"++API_VERSION_2 = "2"++# X rejects a `start_time` before this instant, so it is the floor for a first incremental run.+EARLIEST_START_TIME = "2010-11-06T00:00:00Z"++# X returns only `id`, `text` and `edit_history_tweet_ids` unless the request asks for more. Every+# name below is readable with an app-only bearer token: `non_public_metrics`, `organic_metrics` and+# `promoted_metrics` need a user context, and a single unreadable name fails the whole request.+POST_FIELDS = ",".join(+ (+ "attachments",+ "author_id",+ "conversation_id",+ "created_at",+ "edit_controls",+ "edit_history_tweet_ids",+ "entities",+ "geo",+ "id",+ "in_reply_to_user_id",+ "lang",+ "note_tweet",+ "possibly_sensitive",+ "public_metrics",+ "referenced_tweets",+ "reply_settings",+ "text",+ "withheld",+ )+)++USER_FIELDS = ",".join(+ (+ "created_at",+ "description",+ "entities",+ "id",+ "location",+ "most_recent_tweet_id",+ "name",+ "pinned_tweet_id",+ "profile_image_url",+ "protected",+ "public_metrics",+ "url",+ "username",+ "verified",+ "verified_type",+ "withheld",+ )+)++LIST_FIELDS = ",".join(+ (+ "created_at",+ "description",+ "follower_count",+ "id",+ "member_count",+ "name",+ "owner_id",+ "private",+ )+)+++@dataclass(frozen=True)+class TwitterEndpointConfig:+ name: str+ path: str+ extra_params: dict[str, str]+ page_size: int+ # True for the per-account endpoints, whose path carries the numeric user id. The source form+ # takes a handle, so those paths are formatted after a lookup resolves the handle to an id.+ needs_user_id: bool = True+ primary_key: str = "id"+ partition_key: str | None = None+ # The API's server-side lower-bound filter on the resource's own timestamp. None means the+ # endpoint has no time filter, so it can only sync as a full refresh.+ start_time_param: str | None = None+ # The order rows arrive in. X serves its timelines newest-first and offers no way to reverse+ # them, so the pipeline must not checkpoint the watermark mid-sync.+ sort_mode: SortMode = "asc"+++TWITTER_ENDPOINTS: dict[str, TwitterEndpointConfig] = {+ "Profile": TwitterEndpointConfig(+ name="Profile",+ path="/2/users/by",+ extra_params={"user.fields": USER_FIELDS},+ page_size=1,+ needs_user_id=False,+ ),+ "Posts": TwitterEndpointConfig(+ name="Posts",+ path="/2/users/{user_id}/tweets",+ extra_params={"tweet.fields": POST_FIELDS},+ page_size=100,+ partition_key="created_at",+ start_time_param="start_time",+ sort_mode="desc",+ ),+ "Mentions": TwitterEndpointConfig(+ name="Mentions",+ path="/2/users/{user_id}/mentions",+ extra_params={"tweet.fields": POST_FIELDS},+ page_size=100,+ partition_key="created_at",+ start_time_param="start_time",+ sort_mode="desc",+ ),+ "LikedPosts": TwitterEndpointConfig(+ name="LikedPosts",+ path="/2/users/{user_id}/liked_tweets",+ extra_params={"tweet.fields": POST_FIELDS},+ page_size=100,+ partition_key="created_at",+ sort_mode="desc",+ ),+ "Followers": TwitterEndpointConfig(+ name="Followers",+ path="/2/users/{user_id}/followers",+ extra_params={"user.fields": USER_FIELDS},+ page_size=1000,+ partition_key="created_at",+ ),+ "Following": TwitterEndpointConfig(+ name="Following",+ path="/2/users/{user_id}/following",+ extra_params={"user.fields": USER_FIELDS},+ page_size=1000,+ partition_key="created_at",+ ),+ "OwnedLists": TwitterEndpointConfig(+ name="OwnedLists",+ path="/2/users/{user_id}/owned_lists",+ extra_params={"list.fields": LIST_FIELDS},+ page_size=100,+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(TWITTER_ENDPOINTS)++# Only the two timeline endpoints take a server-side `start_time`. The rest page a cursor with no+# time filter, so advertising a cursor field on them would make every run re-read the full list.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [incremental_field("created_at")] for name, config in TWITTER_ENDPOINTS.items() if config.start_time_param+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/source.pyindex 0ca3aa16d933..88e1522e0000 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/source.py@@ -1,29 +1,146 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.twitter import (TwitterSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter.settings import (+ API_VERSION_2,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter.twitter import (+ TwitterResumeConfig,+ endpoint_permissions,+ twitter_source,+ validate_credentials as validate_twitter_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class TwitterSource(SimpleSource[TwitterSourceConfig]):+class TwitterSource(ResumableSource[TwitterSourceConfig, TwitterResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = (API_VERSION_2,)+ default_version = API_VERSION_2+ api_docs_url = "https://docs.x.com/x-api/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.TWITTER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.x.com": "X rejected the bearer token. Generate a new one in the X developer portal and reconnect the source.",+ "403 Client Error: Forbidden for url: https://api.x.com": "Your X app cannot read this endpoint. Check the project's API access and credit balance in the X developer portal, or stop syncing this table.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.twitter.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: TwitterSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: TwitterSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_twitter_credentials(config.bearer_token, config.username)++ def get_endpoint_permissions(+ self, config: TwitterSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None+ ) -> dict[str, str | None]:+ return endpoint_permissions(config.bearer_token, config.username, endpoints)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TwitterResumeConfig]:+ return ResumableSourceManager[TwitterResumeConfig](inputs, TwitterResumeConfig)++ def source_for_pipeline(+ self,+ config: TwitterSourceConfig,+ resumable_source_manager: ResumableSourceManager[TwitterResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return twitter_source(+ bearer_token=config.bearer_token,+ username=config.username,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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=ExternalDataSourceType.TWITTER,category=DataWarehouseSourceCategory.COMMUNICATION,label="Twitter",- # Twitter was rebranded to X; match the terms users now search by.keywords=["x", "x.com"],+ caption=(+ "Sync one X account's profile, posts, mentions and audience. "+ "**X charges your own developer project for every post this source reads.** "+ "Create an app in the [X developer portal](https://developer.x.com/en/portal/dashboard), "+ "attach it to a project that has API credits, then copy the app's **Bearer Token**."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/twitter",iconPath="/static/services/twitter.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="bearer_token",+ label="Bearer token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Account handle",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="posthog",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/tests/test_twitter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/tests/test_twitter.pynew file mode 100644index 000000000000..e0711bc558a6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/tests/test_twitter.py@@ -0,0 +1,372 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter.settings import TWITTER_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter.twitter import (+ TwitterResumeConfig,+ TwitterUserNotFoundError,+ endpoint_permissions,+ normalize_username,+ resolve_user_id,+ to_rfc3339,+ twitter_source,+ validate_credentials,+)++_SESSION_TARGET = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+_DIRECT_SESSION_TARGET = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.twitter.twitter.make_tracked_session"+)+++def _json_response(body: dict[str, Any], status_code: int = 200) -> Response:+ response = Response()+ response.status_code = status_code+ response._content = json.dumps(body).encode()+ response.headers["Content-Type"] = "application/json"+ return response+++def _pages(response: SourceResponse) -> list[list[dict[str, Any]]]:+ # SourceResponse.items is typed for async sources too; every X endpoint is synchronous.+ return list(cast(Iterable[list[dict[str, Any]]], response.items()))+++def _query(url: str) -> dict[str, list[str]]:+ return parse_qs(urlsplit(url).query)+++class TestNormalizeUsername:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("posthog", "posthog"),+ ("@posthog", "posthog"),+ (" @PostHog_1 ", "PostHog_1"),+ ("a" * 15, "a" * 15),+ ],+ )+ def test_accepts_a_handle(self, raw: str, expected: str) -> None:+ assert normalize_username(raw) == expected++ @pytest.mark.parametrize(+ "raw",+ [+ "",+ "@",+ "a" * 16,+ "post hog",+ "post-hog",+ # A pasted profile URL would otherwise be interpolated straight into the request path.+ "https://x.com/posthog",+ "posthog/../../2/users/me",+ ],+ )+ def test_rejects_anything_else(self, raw: str) -> None:+ with pytest.raises(ValueError):+ normalize_username(raw)+++class TestToRfc3339:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (datetime(2024, 3, 1, 12, 30, 45, tzinfo=UTC), "2024-03-01T12:30:45Z"),+ # A naive watermark is read as UTC rather than the worker's local zone.+ (datetime(2024, 3, 1, 12, 30, 45), "2024-03-01T12:30:45Z"),+ # Microseconds are dropped: X takes second granularity only.+ (datetime(2024, 3, 1, 12, 30, 45, 987654, tzinfo=UTC), "2024-03-01T12:30:45Z"),+ # The endpoint's `initial_value` arrives as a string on the first incremental run.+ ("2010-11-06T00:00:00Z", "2010-11-06T00:00:00Z"),+ ("2024-03-01T12:30:45+00:00", "2024-03-01T12:30:45Z"),+ ],+ )+ def test_formats_a_watermark(self, value: Any, expected: str) -> None:+ assert to_rfc3339(value) == expected++ def test_converts_a_non_utc_offset(self) -> None:+ moment = datetime.fromisoformat("2024-03-01T12:00:00+02:00")+ assert to_rfc3339(moment) == "2024-03-01T10:00:00Z"+++class TestResolveUserId:+ def test_returns_the_numeric_id(self) -> None:+ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ MockSession.return_value.get.return_value = _json_response({"data": {"id": "2244994945"}})+ assert resolve_user_id("token", "@posthog") == "2244994945"++ sent_url = MockSession.return_value.get.call_args.args[0]+ assert sent_url == "https://api.x.com/2/users/by/username/posthog"++ def test_raises_when_the_handle_has_no_account(self) -> None:+ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ MockSession.return_value.get.return_value = _json_response(+ {"errors": [{"title": "Not Found Error", "detail": "Could not find user"}]}+ )+ with pytest.raises(TwitterUserNotFoundError):+ resolve_user_id("token", "posthog")+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "body", "expected_ok", "expected_fragment"),+ [+ (200, {"data": {"id": "1"}}, True, None),+ (401, {"title": "Unauthorized"}, False, "rejected that bearer token"),+ (403, {"title": "Forbidden"}, False, "API credits"),+ (500, {}, False, "HTTP 500"),+ # X answers an unknown handle with 200 and an `errors` array, not a 404.+ (200, {"errors": [{"title": "Not Found Error"}]}, False, "no account with the handle"),+ ],+ )+ def test_maps_each_response_to_a_message(+ self, status_code: int, body: dict[str, Any], expected_ok: bool, expected_fragment: str | None+ ) -> None:+ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ MockSession.return_value.get.return_value = _json_response(body, status_code=status_code)+ ok, message = validate_credentials("token", "posthog")++ assert ok is expected_ok+ if expected_fragment is None:+ assert message is None+ else:+ assert message is not None and expected_fragment in message++ def test_rejects_a_malformed_handle_without_calling_the_api(self) -> None:+ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ ok, message = validate_credentials("token", "https://x.com/posthog")++ assert ok is False+ assert message is not None and "handle" in message+ MockSession.return_value.get.assert_not_called()+++class TestEndpointPermissions:+ def test_reports_the_tables_the_app_cannot_read(self) -> None:+ responses = {+ "/2/users/by/username/posthog": _json_response({"data": {"id": "7"}}),+ "/2/users/by": _json_response({"data": [{"id": "7"}]}),+ "/2/users/7/tweets": _json_response({"data": []}),+ "/2/users/7/followers": _json_response({"title": "Forbidden"}, status_code=403),+ }++ def fake_get(url: str, **_kwargs: Any) -> Response:+ return responses[urlsplit(url).path]++ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ MockSession.return_value.get.side_effect = fake_get+ result = endpoint_permissions("token", "posthog", ["Profile", "Posts", "Followers"])++ assert result["Profile"] is None+ assert result["Posts"] is None+ assert result["Followers"] is not None and "API access" in result["Followers"]++ def test_reports_nothing_when_the_handle_will_not_resolve(self) -> None:+ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ MockSession.return_value.get.return_value = _json_response({"errors": [{"title": "Not Found Error"}]})+ assert endpoint_permissions("token", "posthog", ["Posts"]) == {}++ def test_treats_a_network_failure_as_reachable(self) -> None:+ def fake_get(url: str, **_kwargs: Any) -> Response:+ if urlsplit(url).path.endswith("/username/posthog"):+ return _json_response({"data": {"id": "7"}})+ raise OSError("connection reset")++ with patch(_DIRECT_SESSION_TARGET) as MockSession:+ MockSession.return_value.get.side_effect = fake_get+ assert endpoint_permissions("token", "posthog", ["Posts"]) == {"Posts": None}+++class TestTwitterSourceRequests:+ """Request shaping, pagination and resume, driven through ``rest_api_resource``."""++ def _drive(+ self,+ endpoint: str,+ responses: list[Response],+ *,+ manager: MagicMock | None = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[str], list[list[dict[str, Any]]], MagicMock]:+ if manager is None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_urls: list[str] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_urls.append(request.url)+ return next(response_iter)++ with (+ patch(_DIRECT_SESSION_TARGET) as MockLookupSession,+ patch(_SESSION_TARGET) as MockSession,+ ):+ MockLookupSession.return_value.get.return_value = _json_response({"data": {"id": "7"}})+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req.prepare()+ mock_session.send.side_effect = fake_send++ response = twitter_source(+ bearer_token="token",+ username="posthog",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ return sent_urls, _pages(response), manager++ def test_full_refresh_omits_the_time_filter(self) -> None:+ sent_urls, pages, _ = self._drive("Posts", [_json_response({"data": [{"id": "1"}], "meta": {}})])++ assert urlsplit(sent_urls[0]).path == "/2/users/7/tweets"+ params = _query(sent_urls[0])+ assert "start_time" not in params+ assert params["max_results"] == ["100"]+ assert pages == [[{"id": "1"}]]++ def test_incremental_run_sends_the_watermark_as_start_time(self) -> None:+ sent_urls, _, _ = self._drive(+ "Posts",+ [_json_response({"data": [{"id": "1"}], "meta": {}})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 3, 1, 12, 0, 0, tzinfo=UTC),+ )++ assert _query(sent_urls[0])["start_time"] == ["2024-03-01T12:00:00Z"]++ def test_first_incremental_run_falls_back_to_the_api_floor(self) -> None:+ sent_urls, _, _ = self._drive(+ "Posts",+ [_json_response({"data": [{"id": "1"}], "meta": {}})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert _query(sent_urls[0])["start_time"] == ["2010-11-06T00:00:00Z"]++ @pytest.mark.parametrize("endpoint", ["LikedPosts", "Followers", "Following", "OwnedLists"])+ def test_endpoints_without_a_time_filter_never_send_one(self, endpoint: str) -> None:+ sent_urls, _, _ = self._drive(+ endpoint,+ [_json_response({"data": [{"id": "1"}], "meta": {}})],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 3, 1, tzinfo=UTC),+ )++ assert "start_time" not in _query(sent_urls[0])++ def test_profile_queries_the_handle_without_resolving_an_id(self) -> None:+ sent_urls, pages, _ = self._drive("Profile", [_json_response({"data": [{"id": "7", "username": "posthog"}]})])++ assert urlsplit(sent_urls[0]).path == "/2/users/by"+ assert _query(sent_urls[0])["usernames"] == ["posthog"]+ assert pages == [[{"id": "7", "username": "posthog"}]]++ def test_follows_the_next_token_and_saves_it_after_each_page(self) -> None:+ sent_urls, pages, manager = self._drive(+ "Posts",+ [+ _json_response({"data": [{"id": "1"}], "meta": {"next_token": "page2"}}),+ _json_response({"data": [{"id": "2"}], "meta": {}}),+ ],+ )++ assert "pagination_token" not in _query(sent_urls[0])+ assert _query(sent_urls[1])["pagination_token"] == ["page2"]+ assert [row["id"] for page in pages for row in page] == ["1", "2"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [TwitterResumeConfig(pagination_token="page2")]++ def test_terminal_page_saves_no_state(self) -> None:+ _, _, manager = self._drive("Posts", [_json_response({"data": [{"id": "1"}], "meta": {}})])++ manager.save_state.assert_not_called()++ def test_resume_seeds_the_saved_pagination_token(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = TwitterResumeConfig(pagination_token="saved")++ sent_urls, _, _ = self._drive("Posts", [_json_response({"data": [{"id": "9"}], "meta": {}})], manager=manager)++ assert _query(sent_urls[0])["pagination_token"] == ["saved"]++ def test_does_not_load_state_when_it_cannot_resume(self) -> None:+ _, _, manager = self._drive("Posts", [_json_response({"data": [{"id": "1"}], "meta": {}})])++ manager.load_state.assert_not_called()++ def test_an_empty_timeline_yields_no_rows(self) -> None:+ # X drops the `data` key entirely when an account has no posts in the window.+ _, pages, _ = self._drive("Posts", [_json_response({"meta": {"result_count": 0}})])++ assert [row for page in pages for row in page] == []+++class TestTwitterSourceResponse:+ def test_timelines_declare_the_order_x_returns(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ response = twitter_source(+ bearer_token="token",+ username="posthog",+ endpoint="Posts",+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ )++ assert response.sort_mode == "desc"+ assert response.partition_keys == ["created_at"]++ def test_profile_is_not_partitioned(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ response = twitter_source(+ bearer_token="token",+ username="posthog",+ endpoint="Profile",+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ )++ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_an_unknown_endpoint_raises_the_retryable_error(self) -> None:+ with pytest.raises(UnknownResourceError):+ twitter_source(+ bearer_token="token",+ username="posthog",+ endpoint="NotAnEndpoint",+ team_id=1,+ job_id="job",+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),+ db_incremental_field_last_value=None,+ )++ def test_every_endpoint_path_resolves_to_a_single_placeholder(self) -> None:+ # A stray placeholder would reach X verbatim and 404 the whole table.+ for config in TWITTER_ENDPOINTS.values():+ formatted = config.path.format(user_id="7") if config.needs_user_id else config.path+ assert "{" not in formatteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/twitter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/twitter.pynew file mode 100644index 000000000000..bb8ea0ea8e86--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twitter/twitter.py@@ -0,0 +1,301 @@+import re+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import Any, Optional++from requests import Session++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.twitter.settings import (+ BASE_URL,+ EARLIEST_START_TIME,+ TWITTER_ENDPOINTS,+ TwitterEndpointConfig,+)++# An X handle is 1-15 characters of `[A-Za-z0-9_]`. The handle is interpolated into a request URL,+# so anything outside that set is rejected rather than escaped.+_USERNAME_RE = re.compile(r"^[A-Za-z0-9_]{1,15}$")++_REQUEST_TIMEOUT = 30++# Smallest `max_results` every paged endpoint accepts: the post timelines require at least 5, the+# user and list endpoints at least 1. Used for the permission probes, which only need the status.+_PROBE_PAGE_SIZE = 5+++class TwitterUserNotFoundError(Exception):+ """The configured handle resolves to no X account."""+++@frozen+class TwitterResumeConfig:+ pagination_token: str+++def normalize_username(raw: str) -> str:+ """Return the bare handle, or raise when it isn't one X could issue."""+ username = raw.strip().lstrip("@")+ if not _USERNAME_RE.match(username):+ raise ValueError(+ "That doesn't look like an X handle. Enter just the handle (the 'posthog' in "+ "'x.com/posthog'), without the URL."+ )+ return username+++def _session(bearer_token: str) -> Session:+ return make_tracked_session(+ headers={"Authorization": f"Bearer {bearer_token}"},+ redact_values=(bearer_token,),+ )+++def to_rfc3339(value: Any) -> str:+ """Format an incremental watermark as the second-granularity UTC instant X expects.++ The watermark arrives as a ``datetime`` from the warehouse and as a string on the first+ incremental run (the endpoint's ``initial_value``), so both shapes are accepted.+ """+ if isinstance(value, datetime):+ moment = value+ else:+ moment = datetime.fromisoformat(str(value).replace("Z", "+00:00"))++ if moment.tzinfo is None:+ moment = moment.replace(tzinfo=UTC)++ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def resolve_user_id(bearer_token: str, username: str) -> str:+ """Look the handle up as the numeric id every per-account endpoint path needs."""+ response = _session(bearer_token).get(+ f"{BASE_URL}/2/users/by/username/{normalize_username(username)}",+ params={"user.fields": "id"},+ timeout=_REQUEST_TIMEOUT,+ )+ response.raise_for_status()++ user_id = (response.json().get("data") or {}).get("id")+ if not user_id:+ raise TwitterUserNotFoundError(f"X has no account with the handle @{username}")+ return str(user_id)+++def validate_credentials(bearer_token: str, username: str) -> tuple[bool, str | None]:+ try:+ handle = normalize_username(username)+ except ValueError as error:+ return False, str(error)++ response = _session(bearer_token).get(+ f"{BASE_URL}/2/users/by/username/{handle}",+ params={"user.fields": "id"},+ timeout=_REQUEST_TIMEOUT,+ )++ if response.status_code == 401:+ return False, "X rejected that bearer token. Generate a new one in the X developer portal and try again."+ if response.status_code == 403:+ # Unlike a scoped API, X gates whole endpoints on the project's API access, and user+ # lookup is the lowest rung. A 403 here means no table in this source can ever sync, so it+ # is reported at source-create rather than deferred to a per-table probe.+ return (+ False,+ "That token's X app cannot read user lookups. Check the app is attached to a project, "+ "and that the project has API credits, then try again.",+ )+ if response.status_code != 200:+ return False, f"X returned HTTP {response.status_code} for the handle @{handle}."++ if not (response.json().get("data") or {}).get("id"):+ return False, f"X has no account with the handle @{handle}."++ return True, None+++def endpoint_permissions(bearer_token: str, username: str, endpoints: list[str]) -> dict[str, str | None]:+ """Report which tables this token's X app can actually read.++ X gates endpoints per app rather than per scope, so a token that lists posts fine still 403s on+ followers. Probing up front lets the schema picker say which tables to leave off instead of+ letting them fail on their first sync.+ """+ session = _session(bearer_token)+ results: dict[str, str | None] = {}+ user_id: str | None = None++ for name in endpoints:+ config = TWITTER_ENDPOINTS.get(name)+ if config is None:+ continue++ if config.needs_user_id and user_id is None:+ try:+ user_id = resolve_user_id(bearer_token, username)+ except Exception:+ # Nothing can be said per-table when the handle itself won't resolve; source-level+ # validation already reports that case.+ return {}++ path = config.path.format(user_id=user_id) if config.needs_user_id else config.path+ params = {"usernames": normalize_username(username)} if name == "Profile" else {"max_results": _PROBE_PAGE_SIZE}++ try:+ response = session.get(f"{BASE_URL}{path}", params=params, timeout=_REQUEST_TIMEOUT)+ except Exception:+ # A network blip is not a permission answer — report the table as reachable and let the+ # sync surface a real failure.+ results[name] = None+ continue++ if response.status_code == 403:+ results[name] = "Your X app's API access doesn't cover this endpoint."+ elif response.status_code == 401:+ results[name] = "X rejected the bearer token."+ else:+ results[name] = None++ return results+++def get_resource(+ endpoint_config: TwitterEndpointConfig,+ username: str,+ user_id: str | None,+ should_use_incremental_field: bool,+) -> EndpointResource:+ path = endpoint_config.path.format(user_id=user_id) if endpoint_config.needs_user_id else endpoint_config.path++ params: dict[str, Any] = dict(endpoint_config.extra_params)+ if endpoint_config.needs_user_id:+ params["max_results"] = endpoint_config.page_size+ else:+ params["usernames"] = username++ endpoint: Endpoint = {+ "path": path,+ "params": params,+ "data_selector": "data",+ "paginator": SinglePagePaginator()+ if not endpoint_config.needs_user_id+ else JSONResponseCursorPaginator(cursor_path="meta.next_token", cursor_param="pagination_token"),+ }++ if should_use_incremental_field and endpoint_config.start_time_param:+ endpoint["incremental"] = {+ "cursor_path": "created_at",+ "start_param": endpoint_config.start_time_param,+ "initial_value": EARLIEST_START_TIME,+ "convert": to_rfc3339,+ }++ return {+ "name": endpoint_config.name,+ "table_name": endpoint_config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def _iter_pages(+ bearer_token: str,+ username: str,+ endpoint_config: TwitterEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[TwitterResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool,+) -> Iterator[Any]:+ # Resolved here rather than in `twitter_source` so the handle lookup happens on the pipeline's+ # iterator thread with the rest of the endpoint's requests, not while the activity is still+ # assembling the response.+ user_id = resolve_user_id(bearer_token, username) if endpoint_config.needs_user_id else None++ config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {"type": "bearer", "token": bearer_token},+ # The bearer token rides every request, so pin the host and refuse redirects: a 3xx+ # from X must not carry the credential off api.x.com.+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": _REQUEST_TIMEOUT,+ },+ "resources": [get_resource(endpoint_config, username, user_id, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.pagination_token}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("cursor"):+ resumable_source_manager.save_state(TwitterResumeConfig(pagination_token=str(state["cursor"])))++ yield from rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def twitter_source(+ bearer_token: str,+ username: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[TwitterResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> SourceResponse:+ endpoint_config = schema_for_resource(TWITTER_ENDPOINTS, endpoint)++ return SourceResponse(+ name=endpoint,+ items=lambda: _iter_pages(+ bearer_token=bearer_token,+ username=username,+ endpoint_config=endpoint_config,+ team_id=team_id,+ job_id=job_id,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ ),+ primary_keys=[endpoint_config.primary_key],+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )