: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 mention import source (#69349)
Tom Owers14eb052a4637
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 74e05dcf1d75..df6d6e8c1748 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -229,6 +229,7 @@ the row lists both.| mailosaur | HTTP | requests | ✅ || marketstack | HTTP | requests | ✅ || matomo | HTTP | requests | ✅ |+| mention | HTTP | requests | ✅ || meta_ads | HTTP | requests | ✅ || metabase | HTTP | requests | ✅ || mixmax | HTTP | requests | ✅ |@@ -583,7 +584,6 @@ doesn't conflict with concurrent PRs.- marketo- maxio- mendeley-- mention- mercado_ads- mercury- mergediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex e9db61243cb0..97b27225c1a3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2085,7 +2085,7 @@ class MendeleySourceConfig(config.Config):@config.configclass MentionSourceConfig(config.Config):- pass+ access_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.pynew file mode 100644index 000000000000..e034acb42324--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.py@@ -0,0 +1,86 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the official Mention API reference (https://dev.mention.com/current/).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "accounts": {+ "description": "The Mention account associated with the connected access token, including notification preferences and permissions.",+ "docs_url": "https://dev.mention.com/current/src/account/GetAccountMe.html",+ "columns": {+ "id": "Unguessable identifier of the account across the whole Mention API.",+ "name": "Display name of the account owner.",+ "email": "Email address of the account owner.",+ "language_code": "Preferred language of the account.",+ "created_at": "When the account was created.",+ "updated_at": "When the account was last updated.",+ "grouped_email_notification": "Whether the account prefers all notifications grouped into a single email across alerts.",+ "default_email_notification_frequency": "Default frequency of email notifications.",+ "default_desktop_notification_frequency": "Default frequency of desktop notifications.",+ "default_push_notification_frequency": "Default frequency of push notifications.",+ "permissions": "Account-level permissions, such as whether the account can create alerts.",+ },+ },+ "alerts": {+ "description": "Saved monitoring queries (alerts) of the account. Each alert defines the keywords, sources, and languages Mention monitors.",+ "docs_url": "https://dev.mention.com/current/src/account/alert/GetAlerts.html",+ "columns": {+ "id": "Unique identifier of the alert.",+ "name": "Human-readable name of the alert.",+ "query": "Monitoring query definition: included, required, and excluded keywords, plus monitored websites.",+ "languages": "Language codes the alert monitors.",+ "countries": "Country codes the alert is restricted to.",+ "sources": "Sources the alert monitors, such as twitter, news, web, blogs, videos, forums, and images.",+ "blocked_sites": "Sites excluded from the alert's results.",+ "role": "Role of the connected account on this alert.",+ "stats": "Aggregate counters for the alert, such as mentions per folder and unread mention totals.",+ "shares": "Accounts the alert is shared with, including their roles and permissions.",+ "noise_detection": "Whether automatic noise detection is enabled for the alert.",+ "created_at": "When the alert was created.",+ "updated_at": "When the alert was last updated.",+ "quota_used": "Portion of the mentions quota used by the alert.",+ "index_version": "Version of the mentions index backing the alert; governs which mention filters are available.",+ },+ },+ "alert_tags": {+ "description": "Tags defined on each alert, used to organize mentions. One row per tag per alert.",+ "docs_url": "https://dev.mention.com/current/src/account/alert/tag/GetTags.html",+ "columns": {+ "alert_id": "Identifier of the alert the tag belongs to (added by PostHog during sync).",+ "id": "Unique identifier of the tag; mentions stay linked to the tag by id when it is renamed.",+ "name": "Human-readable label of the tag.",+ "mention_count": "Number of mentions carrying the tag.",+ "keywords": "Keywords used for auto-tagging new mentions (maximum of 5).",+ },+ },+ "mentions": {+ "description": "Individual mentions found by each alert: one row per piece of content (news article, tweet, blog post, and so on) matching the alert's query.",+ "docs_url": "https://dev.mention.com/current/src/account/alert/mention/GetMentions.html",+ "columns": {+ "id": "Unique identifier of the mention.",+ "alert_id": "Identifier of the alert that found the mention (normalized to a string by PostHog during sync).",+ "title": "Title of the mentioned content. Not provided for Twitter, Facebook, or Instagram mentions.",+ "description": "Excerpt of the mentioned content. Not provided for Twitter, Facebook, or Instagram mentions.",+ "original_url": "Original URL of the mention, usable for automated lookups.",+ "clickable_url": "URL to use in user-facing contexts.",+ "displayable_url": "URL formatted for display to users.",+ "unique_id": "Stable identifier of the underlying content, typically its URL.",+ "published_at": "When the content was published.",+ "created_at": "When Mention found the mention.",+ "updated_at": "When the mention was last updated.",+ "country": "Country code of the mention.",+ "favorite": "Whether the mention is marked as favorite.",+ "folder": "Folder the mention lives in: inbox, archive, spam, or trash.",+ "read": "Whether the mention has been read.",+ "tone": "Sentiment of the mention: -1 negative, 0 neutral, 1 positive.",+ "source_type": "Type of source the mention came from, such as news, twitter, or web.",+ "source_name": "Name of the source. Not provided for Twitter, Facebook, or Instagram mentions.",+ "source_url": "URL of the source. Not provided for Twitter, Facebook, or Instagram mentions.",+ "language_code": "Language of the mentioned content.",+ "tags": "Tags applied to the mention.",+ "children": "Related duplicate mentions, such as retweets of a tweet.",+ "author_influence": "Influence score and details of the content's author.",+ "metadata": "Source-specific metadata, such as tweet and Twitter user ids.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.pynew file mode 100644index 000000000000..bae824bb0e90--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.py@@ -0,0 +1,322 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urljoin++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.settings import MENTION_ENDPOINTS++MENTION_HOST = "https://api.mention.net"+MENTION_BASE_URL = f"{MENTION_HOST}/api"+# Pinned API version, sent on every request as recommended by the Mention docs.+API_VERSION = "1.19"+# Mentions accept up to limit=1000; 100 keeps pages small while staying well inside the documented+# 3600 list calls per alert per 24h quota.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an access token is genuine. The token is account-wide, so one+# probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/accounts/me"+++class MentionRetryableError(Exception):+ pass+++class MentionResumeConfig:+ # Remaining alert ids for the per-alert fan-out endpoints (current alert first). None means the+ # endpoint is not a fan-out one (or the alert list hasn't been captured yet).+ alert_ids: list[str] | None = None+ # Absolute URL of the next page to fetch, taken from the API's ``_links.more.href``. Cursor+ # pagination is deterministic, so a crashed full-refresh sync resumes from the page after the+ # last one yielded; merge dedupes the re-pulled page on the primary key.+ next_url: str | None = None+++def _headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ "Accept-Version": API_VERSION,+ }+++def _list_url(path: str, limit: int | None = PAGE_SIZE) -> str:+ if limit is None:+ return f"{MENTION_BASE_URL}{path}"+ return f"{MENTION_BASE_URL}{path}?{urlencode({'limit': limit})}"+++def _more_url(payload: dict[str, Any]) -> Optional[str]:+ # ``_links.more.href`` points at the next page of older items and is present only when more+ # exist. The href is host-relative (``/api/...``), so resolve it against the API host.+ links = payload.get("_links")+ if not isinstance(links, dict):+ return None+ more = links.get("more")+ if not (isinstance(more, dict) and isinstance(more.get("href"), str) and more["href"]):+ return None+ # urljoin honours an absolute href, so a tampered response could point the session (which+ # carries the bearer token in its default headers) at another host. Pin the resolved URL to+ # the Mention API before we ever fetch it.+ resolved = urljoin(MENTION_HOST, more["href"])+ if resolved != MENTION_BASE_URL and not resolved.startswith((f"{MENTION_BASE_URL}/", f"{MENTION_BASE_URL}?")):+ raise MentionRetryableError(f"Mention pagination URL {resolved!r} is not on the Mention API host")+ return resolved+++@retry(+ retry=retry_if_exception_type((MentionRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ # ``url`` is already absolute — either an initial list URL or a resolved ``_links.more`` href,+ # so we never re-send paging params (they're baked into the cursor URL).+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ # 429 carries X-Rate-Limit-Reset (a unix timestamp); the per-alert quota window can be+ # hours long, so we back off briefly here and otherwise let the job-level retry policy+ # reschedule the sync.+ raise MentionRetryableError(f"Mention API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Mention API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict):+ raise MentionRetryableError(f"Mention returned an unexpected payload for {url}: {type(data).__name__}")++ return data+++def _rows_from_payload(payload: dict[str, Any], key: str, url: str) -> list[dict[str, Any]]:+ rows = payload.get(key)+ if not isinstance(rows, list):+ raise MentionRetryableError(f"Mention returned an unexpected '{key}' field for {url}")+ return rows+++def _unwrap_alert(item: dict[str, Any]) -> dict[str, Any]:+ # The docs state each listed alert "has the form it would if you did a get request on that+ # specific alert", whose body nests the object under ``alert`` — accept both shapes.+ inner = item.get("alert")+ return inner if isinstance(inner, dict) else item+++def _get_account(session: requests.Session, logger: FilteringBoundLogger) -> dict[str, Any]:+ payload = _fetch_page(session, f"{MENTION_BASE_URL}/accounts/me", logger)+ account = payload.get("account")+ if not isinstance(account, dict) or account.get("id") is None:+ raise MentionRetryableError("Mention returned an unexpected payload for /accounts/me")+ return account+++def _list_all_alert_ids(session: requests.Session, account_id: str, logger: FilteringBoundLogger) -> list[str]:+ alert_ids: list[str] = []+ url: Optional[str] = _list_url(f"/accounts/{account_id}/alerts")+ while url:+ payload = _fetch_page(session, url, logger)+ rows = [_unwrap_alert(row) for row in _rows_from_payload(payload, "alerts", url)]+ for row in rows:+ # ``id`` is the alert's primary key and the fan-out endpoints build their URLs from it,+ # so a missing id is a data error we surface rather than silently drop the alert.+ if row.get("id") is None:+ raise MentionRetryableError(f"Mention returned an alert without an id for {url}")+ alert_ids.append(str(row["id"]))+ url = None if not rows else _more_url(payload)+ return alert_ids+++def _account_rows(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:+ yield [_get_account(session, logger)]+++def _alert_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ resume: MentionResumeConfig | None,+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ if resume and resume.next_url:+ url: Optional[str] = resume.next_url+ logger.debug(f"Mention: resuming alerts from cursor {url}")+ else:+ account_id = str(_get_account(session, logger)["id"])+ url = _list_url(f"/accounts/{account_id}/alerts")++ while url:+ payload = _fetch_page(session, url, logger)+ rows = [_unwrap_alert(row) for row in _rows_from_payload(payload, "alerts", url)]+ if rows:+ yield rows++ # A missing ``_links.more`` marks the end of the collection. An empty page also terminates+ # defensively so a lingering cursor can never produce an infinite loop.+ next_url = _more_url(payload)+ if not next_url or not rows:+ break++ url = next_url+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(MentionResumeConfig(next_url=next_url))+++def _fan_out_alert_ids(+ session: requests.Session,+ account_id: str,+ logger: FilteringBoundLogger,+ resume: MentionResumeConfig | None,+) -> tuple[list[str], str | None]:+ if resume and resume.alert_ids is not None:+ logger.debug(+ f"Mention: resuming fan-out with {len(resume.alert_ids)} alerts remaining, cursor {resume.next_url}"+ )+ return list(resume.alert_ids), resume.next_url+ return _list_all_alert_ids(session, account_id, logger), None+++def _mention_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ resume: MentionResumeConfig | None,+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ account_id = str(_get_account(session, logger)["id"])+ alert_ids, next_url = _fan_out_alert_ids(session, account_id, logger, resume)++ while alert_ids:+ alert_id = alert_ids[0]+ url: Optional[str] = next_url or _list_url(f"/accounts/{account_id}/alerts/{alert_id}/mentions")++ while url:+ payload = _fetch_page(session, url, logger)+ rows = _rows_from_payload(payload, "mentions", url)+ for row in rows:+ # Normalized to a string so the merge key type is consistent across alerts.+ row["alert_id"] = alert_id+ if rows:+ yield rows++ more = _more_url(payload)+ if not more or not rows:+ break++ url = more+ resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids, next_url=url))++ alert_ids = alert_ids[1:]+ next_url = None+ resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids))+++def _alert_tag_rows(+ session: requests.Session,+ logger: FilteringBoundLogger,+ resume: MentionResumeConfig | None,+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ account_id = str(_get_account(session, logger)["id"])+ alert_ids, _ = _fan_out_alert_ids(session, account_id, logger, resume)++ while alert_ids:+ alert_id = alert_ids[0]+ # The tags endpoint is not paginated (its ``_links`` is an empty list in the docs).+ url = _list_url(f"/accounts/{account_id}/alerts/{alert_id}/tags", limit=None)+ payload = _fetch_page(session, url, logger)+ rows = _rows_from_payload(payload, "tags", url)+ for row in rows:+ row["alert_id"] = alert_id+ if rows:+ yield rows++ alert_ids = alert_ids[1:]+ resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids))+++def get_rows(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(headers=_headers(access_token), redact_values=(access_token,))+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if endpoint == "accounts":+ yield from _account_rows(session, logger)+ elif endpoint == "alerts":+ yield from _alert_rows(session, logger, resume, resumable_source_manager)+ elif endpoint == "alert_tags":+ yield from _alert_tag_rows(session, logger, resume, resumable_source_manager)+ elif endpoint == "mentions":+ yield from _mention_rows(session, logger, resume, resumable_source_manager)+ else:+ raise ValueError(f"Unknown Mention endpoint '{endpoint}'")+++def mention_source(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],+) -> SourceResponse:+ config = MENTION_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(access_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the access token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(access_token), redact_values=(access_token,))+ try:+ response = session.get(f"{MENTION_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Mention: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Mention returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(access_token: str) -> tuple[bool, str | None]:+ status, message = check_access(access_token)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Mention access token"+ return False, message or "Could not validate Mention access token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.pynew file mode 100644index 000000000000..f8b1d9d0acd0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.py@@ -0,0 +1,27 @@+from dataclasses import dataclass, field+++@dataclass+class MentionEndpointConfig:+ name: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Mention API list endpoints (https://dev.mention.com/current/). All are full refresh only:+# mentions do expose a `since_id` server-side cursor, but it orders by fetch recency (not a+# timestamp), and it could not be verified against a live account, so we conservatively ship+# full refresh and rely on merge dedupe (see the implementing-warehouse-sources skill).+MENTION_ENDPOINTS: dict[str, MentionEndpointConfig] = {+ "accounts": MentionEndpointConfig(name="accounts"),+ "alerts": MentionEndpointConfig(name="alerts"),+ # Tag ids are documented as unique identifiers, but uniqueness scope (alert vs account) is not+ # stated, so the parent alert id stays in the composite key.+ "alert_tags": MentionEndpointConfig(name="alert_tags", primary_keys=["alert_id", "id"]),+ # Mentions fan out per alert and each row natively carries `alert_id`; the composite key keeps+ # the same content matched by two alerts as two distinct rows.+ "mentions": MentionEndpointConfig(name="mentions", primary_keys=["alert_id", "id"]),+}++ENDPOINTS = tuple(MENTION_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.pyindex 9c1a6d343b7f..2b9a40413784 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MentionSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.mention import (+ MentionResumeConfig,+ mention_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.settings import (+ ENDPOINTS,+ MENTION_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MentionSource(SimpleSource[MentionSourceConfig]):+class MentionSource(ResumableSource[MentionSourceConfig, MentionResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MENTION@@ -24,7 +47,89 @@ class MentionSource(SimpleSource[MentionSourceConfig]):name=SchemaExternalDataSourceType.MENTION,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Mention",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["social listening", "media monitoring", "brand monitoring"],+ caption="""Enter your Mention API access token to pull your monitored accounts, alerts, mentions, and tags into the PostHog Data warehouse.++You can create an access token by registering an API application at [dev.mention.com](https://dev.mention.com). Note that Mention API access is a paid add-on to Mention plans.+""",iconPath="/static/services/mention.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/mention",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.mention.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.mention.net": "Your Mention access token is invalid or has expired. Generate a new token from your API application at dev.mention.com, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.mention.net": "Your Mention access token does not have access to this data. Check that API access is enabled on your Mention plan, then reconnect.",+ }++ def get_schemas(+ self,+ config: MentionSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — mentions expose a `since_id` cursor, but it orders+ # by fetch recency rather than a timestamp, and it could not be verified against a live+ # account, so there is no trustworthy server-side cursor to advance an incremental sync.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: MentionSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The access token is account-wide, so a single probe validates access to every schema.+ return validate_credentials(config.access_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MentionResumeConfig]:+ return ResumableSourceManager[MentionResumeConfig](inputs, MentionResumeConfig)++ def source_for_pipeline(+ self,+ config: MentionSourceConfig,+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in MENTION_ENDPOINTS:+ raise ValueError(f"Unknown Mention schema '{inputs.schema_name}'")++ return mention_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.pynew file mode 100644index 000000000000..124e9ce79707--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.py@@ -0,0 +1,309 @@+from collections.abc import Mapping+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.mention import mention+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.mention import (+ MENTION_BASE_URL,+ MENTION_HOST,+ MentionResumeConfig,+ MentionRetryableError,+ _more_url,+ check_access,+ get_rows,+ mention_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.settings import (+ ENDPOINTS,+ MENTION_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = mention._fetch_page.__wrapped__ # type: ignore[attr-defined]++ME_URL = f"{MENTION_BASE_URL}/accounts/me"+ME_PAYLOAD = {"account": {"id": "acc1", "name": "NASA"}}+++class _FakeResumableManager:+ def __init__(self, state: MentionResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[MentionResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> MentionResumeConfig | None:+ return self._state++ def save_state(self, data: MentionResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: Mapping[str, Any],+ endpoint: str,+ ) -> list[dict]:+ def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:+ assert url in pages, f"unexpected request to {url}"+ return pages[url]++ monkeypatch.setattr(mention, "_fetch_page", fake_fetch)+ monkeypatch.setattr(mention, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ access_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_accounts_yields_single_unwrapped_row(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {ME_URL: ME_PAYLOAD}, "accounts")+ assert rows == [{"id": "acc1", "name": "NASA"}]+ assert manager.saved == []++ def test_alerts_follows_more_link_and_unwraps_items(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ first = f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"+ more_href = "/api/accounts/acc1/alerts?limit=100&cursor=abc"+ second = f"{MENTION_HOST}{more_href}"+ pages = {+ ME_URL: ME_PAYLOAD,+ # The docs show list items in single-GET form ({"alert": {...}}) — both shapes must work.+ first: {"alerts": [{"alert": {"id": 11}}], "_links": {"more": {"href": more_href}}},+ second: {"alerts": [{"id": 22}]},+ }+ rows = self._collect(manager, monkeypatch, pages, "alerts")+ assert rows == [{"id": 11}, {"id": 22}]+ # State is saved once — after the first page, pointing at the resolved absolute cursor URL.+ assert [s.next_url for s in manager.saved] == [second]++ def test_alerts_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ second = f"{MENTION_HOST}/api/accounts/acc1/alerts?limit=100&cursor=abc"+ manager = _FakeResumableManager(MentionResumeConfig(next_url=second))+ # Neither /accounts/me nor the first page may be fetched on resume.+ rows = self._collect(manager, monkeypatch, {second: {"alerts": [{"id": 22}]}}, "alerts")+ assert rows == [{"id": 22}]++ def test_mentions_fan_out_injects_alert_id_and_saves_state(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ alerts_url = f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"+ first_11 = f"{MENTION_BASE_URL}/accounts/acc1/alerts/11/mentions?limit=100"+ more_href = "/api/accounts/acc1/alerts/11/mentions?limit=100&before_date=2024-01-01T00:00:00.0"+ second_11 = f"{MENTION_HOST}{more_href}"+ first_22 = f"{MENTION_BASE_URL}/accounts/acc1/alerts/22/mentions?limit=100"+ pages = {+ ME_URL: ME_PAYLOAD,+ alerts_url: {"alerts": [{"alert": {"id": 11}}, {"alert": {"id": 22}}]},+ first_11: {"mentions": [{"id": "m1", "alert_id": 11}], "_links": {"more": {"href": more_href}}},+ second_11: {"mentions": [{"id": "m2", "alert_id": 11}], "_links": {}},+ first_22: {"mentions": [{"id": "m3", "alert_id": 22}], "_links": {}},+ }+ rows = self._collect(manager, monkeypatch, pages, "mentions")+ # alert_id is normalized to a string so the composite merge key type is consistent.+ assert rows == [+ {"id": "m1", "alert_id": "11"},+ {"id": "m2", "alert_id": "11"},+ {"id": "m3", "alert_id": "22"},+ ]+ assert [(s.alert_ids, s.next_url) for s in manager.saved] == [+ (["11", "22"], second_11),+ (["22"], None),+ ([], None),+ ]++ def test_mentions_resume_skips_completed_alerts_and_uses_cursor(self, monkeypatch: Any) -> None:+ cursor = f"{MENTION_HOST}/api/accounts/acc1/alerts/22/mentions?limit=100&before_date=2024-01-01T00:00:00.0"+ manager = _FakeResumableManager(MentionResumeConfig(alert_ids=["22"], next_url=cursor))+ # Alert 11 and the alerts listing must never be re-fetched; alert 22 resumes mid-pagination.+ pages = {+ ME_URL: ME_PAYLOAD,+ cursor: {"mentions": [{"id": "m4"}], "_links": {}},+ }+ rows = self._collect(manager, monkeypatch, pages, "mentions")+ assert rows == [{"id": "m4", "alert_id": "22"}]++ def test_mentions_empty_page_with_more_link_terminates(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ alerts_url = f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"+ first_11 = f"{MENTION_BASE_URL}/accounts/acc1/alerts/11/mentions?limit=100"+ pages = {+ ME_URL: ME_PAYLOAD,+ alerts_url: {"alerts": [{"alert": {"id": 11}}]},+ # A lingering more link on an empty page must not produce an infinite loop.+ first_11: {"mentions": [], "_links": {"more": {"href": "/api/anything"}}},+ }+ assert self._collect(manager, monkeypatch, pages, "mentions") == []++ def test_alert_tags_injects_alert_id_without_pagination(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ alerts_url = f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"+ tags_url = f"{MENTION_BASE_URL}/accounts/acc1/alerts/11/tags"+ pages = {+ ME_URL: ME_PAYLOAD,+ alerts_url: {"alerts": [{"alert": {"id": 11}}]},+ # The tags endpoint's `_links` is an empty list, not a dict — must not be treated as a cursor.+ tags_url: {"tags": [{"id": 46468, "name": "space"}], "_links": []},+ }+ rows = self._collect(manager, monkeypatch, pages, "alert_tags")+ assert rows == [{"id": 46468, "name": "space", "alert_id": "11"}]+ assert [s.alert_ids for s in manager.saved] == [[]]++ def test_unknown_endpoint_raises(self, monkeypatch: Any) -> None:+ with pytest.raises(ValueError, match="Unknown Mention endpoint 'nope'"):+ self._collect(_FakeResumableManager(), monkeypatch, {}, "nope")+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"mentions": [], "_links": {}}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(MentionRetryableError):+ _fetch_page_unwrapped(session, ME_URL, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, ME_URL, MagicMock())++ def test_non_dict_payload_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": "a"}])+ with pytest.raises(MentionRetryableError):+ _fetch_page_unwrapped(session, ME_URL, MagicMock())++ def test_success_returns_payload_without_extra_params(self) -> None:+ body = {"mentions": [{"id": "m1"}], "_links": {}}+ session = self._session_returning(200, body)+ url = f"{MENTION_BASE_URL}/accounts/acc1/alerts/11/mentions?limit=100&before_date=x"+ assert _fetch_page_unwrapped(session, url, MagicMock()) == body+ args, kwargs = session.get.call_args+ assert args[0] == url+ # The cursor URL already carries paging; we must not re-send page params.+ assert "params" not in kwargs+++class TestMoreUrl:+ @parameterized.expand(+ [+ ("relative_href", {"_links": {"more": {"href": "/api/a?cursor=x"}}}, f"{MENTION_HOST}/api/a?cursor=x"),+ ("absolute_href", {"_links": {"more": {"href": f"{MENTION_HOST}/api/b"}}}, f"{MENTION_HOST}/api/b"),+ ("no_more", {"_links": {"pull": {"href": "/api/a"}}}, None),+ ("links_is_empty_list", {"_links": []}, None),+ ("missing_links", {"mentions": []}, None),+ ("empty_href", {"_links": {"more": {"href": ""}}}, None),+ ]+ )+ def test_more_url(self, _name: str, payload: dict[str, Any], expected: Optional[str]) -> None:+ assert _more_url(payload) == expected++ @parameterized.expand(+ [+ ("absolute_off_host", "https://evil.com/api/x"),+ ("protocol_relative", "//evil.com/api"),+ ("lookalike_host", "https://api.mention.net.evil.com/api/x"),+ ]+ )+ def test_more_url_rejects_off_host_pagination(self, _name: str, href: str) -> None:+ # A tampered cursor must never send the bearer-token session to another host.+ with pytest.raises(MentionRetryableError, match="not on the Mention API host"):+ _more_url({"_links": {"more": {"href": href}}})+++class TestCheckAccess:+ def _session(self, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Mention returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ with patch.object(mention, "make_tracked_session", return_value=self._session(response)):+ assert check_access("tok") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(mention, "make_tracked_session", return_value=session):+ status, message = check_access("tok")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid Mention access token"),+ ("forbidden", 403, False, "Invalid Mention access token"),+ ("server_error", 500, False, "Mention returned HTTP 500"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with patch.object(mention, "make_tracked_session", return_value=self._session(response)):+ assert validate_credentials("tok") == (expected_valid, expected_message)+++class TestMentionSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = mention_source(+ access_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == MENTION_ENDPOINTS[endpoint].primary_keys+ # No stable creation timestamp is guaranteed across every object, so we don't partition.+ assert response.partition_mode is None++ def test_fan_out_endpoints_carry_parent_id_in_key(self) -> None:+ # Fan-out children aggregate rows from every alert; the parent id must be in the merge key.+ assert MENTION_ENDPOINTS["mentions"].primary_keys == ["alert_id", "id"]+ assert MENTION_ENDPOINTS["alert_tags"].primary_keys == ["alert_id", "id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.pynew file mode 100644index 000000000000..6ee889b8c06a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.py@@ -0,0 +1,121 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MentionSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.mention import MentionResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.mention.source import MentionSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestMentionSource:+ def setup_method(self) -> None:+ self.source = MentionSource()+ self.team_id = 123+ self.config = MentionSourceConfig(access_token="tok")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.MENTION++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Mention"+ assert config.label == "Mention"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/mention"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["access_token"]++ def test_access_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret access token; the base URL is hardcoded, so there is no+ # non-secret field an editor could retarget to reuse a preserved token against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["mentions"])+ assert len(schemas) == 1+ assert schemas[0].name == "mentions"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.mention.net/api/accounts/me",),+ ("403 Client Error: Forbidden for url: https://api.mention.net/api/accounts/acc1/alerts",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.mention.net/api/accounts/me",),+ ("429 Client Error: Too Many Requests for url: https://api.mention.net/api/accounts/acc1/alerts",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mention.source.validate_credentials")+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ # The source method forwards the account access token to the shared validator and returns its result verbatim.+ mock_validate.return_value = (False, "Invalid Mention access token")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid Mention access token")+ mock_validate.assert_called_once_with("tok")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MentionResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.mention.source.mention_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "mentions"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["access_token"] == "tok"+ assert kwargs["endpoint"] == "mentions"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Mention schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)