: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 newsdata import source (#67817)
Tom Owers5a62ce194cdc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d8b9514fdccb..2d67a60055f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -216,6 +216,7 @@ the row lists both.| mysql | DB protocol | pymysql | ➖ || new_york_times | HTTP | requests | ✅ || news_api | HTTP | requests | ✅ |+| newsdata | HTTP | requests | ✅ || okta | HTTP | requests | ✅ || nocrm | HTTP | requests | ✅ || northpass_lms | HTTP | requests | ✅ |@@ -536,7 +537,6 @@ doesn't conflict with concurrent PRs.- netsuite- new_relic- news_api-- newsdata- nexiopay- ninjaone_rmm- nocrmdiff --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 625ad2fa5c4f..fb19fe365c83 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@@ -2149,7 +2149,7 @@ class NewsApiSourceConfig(config.Config):@config.configclass NewsDataSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/canonical_descriptions.pynew file mode 100644index 000000000000..484dc6ac81fb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/canonical_descriptions.py@@ -0,0 +1,81 @@+"""Canonical, documentation-sourced descriptions for NewsData.io endpoints and columns.++Sourced from the official NewsData.io API reference (https://newsdata.io/documentation).+Keyed by the endpoint names in `settings.py` `NEWSDATA_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced NewsData.io table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# The latest, archive, and crypto endpoints all return the same news-article shape.+_ARTICLE_COLUMNS = {+ "article_id": "Unique identifier for the news article.",+ "title": "The article's headline.",+ "link": "URL of the original article.",+ "keywords": "Keywords associated with the article.",+ "creator": "Author(s) of the article.",+ "video_url": "URL of a video embedded in the article, if any.",+ "description": "A short summary of the article.",+ "content": "The full text content of the article (available on paid plans).",+ "pubDate": "Date and time the article was published, in UTC.",+ "pubDateTZ": "Timezone of the original publish date.",+ "image_url": "URL of the article's main image.",+ "source_id": "Identifier of the news source that published the article.",+ "source_priority": "Ranking of the source's importance/authority.",+ "source_name": "Display name of the news source.",+ "source_url": "Home URL of the news source.",+ "source_icon": "URL of the news source's icon.",+ "language": "Language the article is written in.",+ "country": "Countries the article is relevant to.",+ "category": "Categories the article belongs to (e.g. business, technology).",+ "sentiment": "Overall sentiment of the article (positive, neutral, or negative).",+ "sentiment_stats": "Per-sentiment confidence breakdown for the article.",+ "ai_tag": "AI-generated topic tags for the article.",+ "ai_region": "AI-detected regions mentioned in the article.",+ "ai_org": "AI-detected organizations mentioned in the article.",+ "duplicate": "Whether the article is flagged as a duplicate of another.",+}++_LATEST_DOCS = "https://newsdata.io/documentation/#latest-news"+_ARCHIVE_DOCS = "https://newsdata.io/documentation/#news-archive"+_CRYPTO_DOCS = "https://newsdata.io/documentation/#crypto-news"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "latest": {+ "description": "Real-time news articles from the last 48 hours across sources worldwide.",+ "docs_url": _LATEST_DOCS,+ "columns": _ARTICLE_COLUMNS,+ },+ "archive": {+ "description": "Historical news articles (up to 7 years) filterable by publish date.",+ "docs_url": _ARCHIVE_DOCS,+ "columns": _ARTICLE_COLUMNS,+ },+ "crypto": {+ "description": "Cryptocurrency-related news articles filterable by publish date and coin.",+ "docs_url": _CRYPTO_DOCS,+ "columns": {+ **_ARTICLE_COLUMNS,+ "coin": "Cryptocurrency coins the article relates to (e.g. btc, eth).",+ },+ },+ "sources": {+ "description": "Catalog of news sources available through NewsData.io.",+ "docs_url": "https://newsdata.io/documentation/#news-sources",+ "columns": {+ "id": "Unique identifier for the news source.",+ "name": "Display name of the news source.",+ "url": "Home URL of the news source.",+ "icon": "URL of the news source's icon.",+ "priority": "Ranking of the source's importance/authority.",+ "description": "A short description of the news source.",+ "category": "Categories the source primarily covers.",+ "language": "Languages the source publishes in.",+ "country": "Countries the source operates in.",+ "last_fetch": "Time the source was last fetched by NewsData.io.",+ "total_article": "Total number of articles available from the source.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/newsdata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/newsdata.pynew file mode 100644index 000000000000..a38622eb423c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/newsdata.py@@ -0,0 +1,221 @@+import dataclasses+from collections.abc import 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 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.newsdata.settings import (+ NEWSDATA_ENDPOINTS,+ NewsDataEndpointConfig,+)++NEWSDATA_BASE_URL = "https://newsdata.io/api/1"++# One request grabs a plan-limited page (10 free / 50 paid), so a page never approaches the batch+# size threshold — we accumulate several pages before handing a batch to the pipeline.+_BATCH_SIZE = 2000+++class NewsDataRetryableError(Exception):+ """Raised for 429/5xx responses so tenacity retries with backoff."""+++class NewsDataError(Exception):+ """Raised for permanent API failures (unsupported param, quota exhausted) that must not retry."""+++class NewsDataResumeConfig:+ # Opaque `nextPage` cursor token to resume pagination from. None means "start at the first page".+ next_page: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ # NewsData accepts the key either as an `apikey` query param or the `X-ACCESS-KEY` header. We use+ # the header so the secret never lands in a logged request URL.+ return {"X-ACCESS-KEY": api_key, "Accept": "application/json"}+++def _to_from_date(value: Any) -> str | None:+ """Reduce an incremental watermark to the `YYYY-MM-DD` string NewsData's `from_date` expects.++ The watermark comes back as a datetime (parsed by the pipeline), a date, or a raw string+ depending on how it was stored; NewsData's date filter is day-granular either way.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.astimezone(UTC).date().isoformat() if value.tzinfo else value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ # Fall back to the leading YYYY-MM-DD of a string like "2024-01-15 12:34:56".+ return str(value)[:10]+++def _build_query_params(+ config: NewsDataEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, str]:+ """Build the endpoint's query params (excluding the cursor, which is added per page).++ Only `from_date` is applied, and only for date-filter endpoints: on the first incremental sync+ it floors the crawl at a trailing lookback window, and on later syncs it advances from the stored+ watermark. Full-refresh endpoints send no params. `size` is intentionally omitted — the page size+ is plan-capped and passing an over-cap value 4xxs, so we let the API apply its own default.+ """+ if not (config.supports_date_filter and should_use_incremental_field):+ return {}++ from_date = _to_from_date(db_incremental_field_last_value)+ if from_date is None and config.default_lookback_days is not None:+ from_date = (datetime.now(UTC) - timedelta(days=config.default_lookback_days)).date().isoformat()++ return {"from_date": from_date} if from_date else {}+++def _raise_for_error_body(payload: dict[str, Any], page_url: str) -> None:+ """NewsData signals problems in the body (`{"status": "error", "results": {...}}`).++ Retryable rate-limit errors still arrive as HTTP 429 and are handled in `_fetch_page`; anything+ left here (unsupported params, quota exhaustion) is a hard error worth surfacing.+ """+ if payload.get("status") == "error":+ results = payload.get("results")+ message = results.get("message") if isinstance(results, dict) else str(results)+ raise NewsDataError(f"NewsData API returned error status: {message} (url={page_url})")+++@retry(+ retry=retry_if_exception_type(+ (+ NewsDataRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(page_url, headers=headers, timeout=60)++ # 429 (rate limit / daily credit throttle) and transient 5xx are retryable; everything else that+ # isn't ok is a permanent failure (bad key, unsupported param) raised via raise_for_status.+ if response.status_code == 429 or response.status_code >= 500:+ raise NewsDataRetryableError(f"NewsData API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"NewsData API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ # The sources catalog is the cheapest authenticated probe: no pagination, small body, and it only+ # needs a valid key. An invalid or missing key returns HTTP 401.+ url = f"{NEWSDATA_BASE_URL}/sources"+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _page_url(config: NewsDataEndpointConfig, params: dict[str, str], next_page: str | None) -> str:+ page_params = dict(params)+ if next_page:+ page_params["page"] = next_page+ query = urlencode(page_params)+ base = f"{NEWSDATA_BASE_URL}{config.path}"+ return f"{base}?{query}" if query else base+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewsDataResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = NEWSDATA_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive between requests.+ # `redact_values` masks the API key anywhere it surfaces in logged/captured telemetry.+ session = make_tracked_session(redact_values=(api_key,))++ params = _build_query_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ next_page = resume.next_page if resume else None+ if next_page:+ logger.debug(f"NewsData: resuming {endpoint} from cursor")++ batch: list[dict[str, Any]] = []+ while True:+ url = _page_url(config, params, next_page)+ data = _fetch_page(session, url, headers, logger)+ _raise_for_error_body(data, url)++ results = data.get("results") or []+ batch.extend(results)++ # `nextPage` is an opaque cursor token; its absence (or a non-paginating endpoint) ends the walk.+ next_page = data.get("nextPage") if config.supports_pagination else None++ if len(batch) >= _BATCH_SIZE:+ yield batch+ batch = []+ # Save AFTER yielding so a crash re-yields the last batch (merge dedupes on the primary+ # key) rather than skipping it. Only persist when more pages remain.+ if next_page:+ resumable_source_manager.save_state(NewsDataResumeConfig(next_page=next_page))++ if not next_page:+ break++ if batch:+ yield batch+++def newsdata_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NewsDataResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = NEWSDATA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ 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=config.primary_keys,+ sort_mode=config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/settings.pynew file mode 100644index 000000000000..31b7f1175ea2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/settings.py@@ -0,0 +1,87 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class NewsDataEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ primary_keys: list[str] = field(default_factory=lambda: ["article_id"])+ # Stable datetime field used both for partitioning and (where the endpoint supports a+ # server-side date filter) as the incremental cursor. Publish date never changes, so it's a+ # safe partition key. None disables partitioning (e.g. the sources catalog has no timestamp).+ partition_key: Optional[str] = None+ # True only for endpoints that accept the `from_date`/`to_date` query params (verified against+ # the live API: rejected on /latest, accepted on /archive and /crypto). Drives whether the+ # endpoint can sync incrementally via a genuine server-side timestamp filter.+ supports_date_filter: bool = False+ # /sources returns the full catalog in a single response and rejects the `page` param, so+ # cursor pagination is skipped for it.+ supports_pagination: bool = True+ # First incremental sync floor: instead of crawling the entire (up to 7-year) archive, the very+ # first sync only pulls the trailing N days. Later syncs advance from the stored watermark.+ default_lookback_days: Optional[int] = None+ # NewsData returns results newest-first and exposes no sort control, so date-filtered endpoints+ # sync in descending order (the pipeline commits the incremental watermark only once the run+ # completes — safe for a newest-first API).+ sort_mode: Literal["asc", "desc"] = "asc"+ should_sync_default: bool = True+++def _pub_date_incremental_fields() -> list[IncrementalField]:+ return [+ {+ "label": "pubDate",+ "type": IncrementalFieldType.DateTime,+ "field": "pubDate",+ "field_type": IncrementalFieldType.DateTime,+ },+ ]+++NEWSDATA_ENDPOINTS: dict[str, NewsDataEndpointConfig] = {+ # Real-time news from the last 48 hours. No server-side date filter, so full refresh only.+ "latest": NewsDataEndpointConfig(+ name="latest",+ path="/latest",+ partition_key="pubDate",+ incremental_fields=[],+ ),+ # Historical news (up to 7 years). `from_date`/`to_date` filter server-side, enabling incremental.+ "archive": NewsDataEndpointConfig(+ name="archive",+ path="/archive",+ partition_key="pubDate",+ supports_date_filter=True,+ default_lookback_days=30,+ sort_mode="desc",+ incremental_fields=_pub_date_incremental_fields(),+ ),+ # Crypto-specific news. Same date-filter/pagination shape as archive.+ "crypto": NewsDataEndpointConfig(+ name="crypto",+ path="/crypto",+ partition_key="pubDate",+ supports_date_filter=True,+ default_lookback_days=30,+ sort_mode="desc",+ incremental_fields=_pub_date_incremental_fields(),+ ),+ # Catalog of available news sources. Single-response, no pagination or date filter.+ "sources": NewsDataEndpointConfig(+ name="sources",+ path="/sources",+ primary_keys=["id"],+ supports_pagination=False,+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(NEWSDATA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in NEWSDATA_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/source.pyindex e324c12b4d4d..6c383db1afad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/source.py@@ -1,19 +1,43 @@-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 NewsDataSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.newsdata import (+ NewsDataResumeConfig,+ newsdata_source,+ validate_credentials as validate_newsdata_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NEWSDATA_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NewsDataSource(SimpleSource[NewsDataSourceConfig]):+class NewsDataSource(ResumableSource[NewsDataSourceConfig, NewsDataResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NEWSDATA@@ -24,7 +48,94 @@ class NewsDataSource(SimpleSource[NewsDataSourceConfig]):name=SchemaExternalDataSourceType.NEWS_DATA,category=DataWarehouseSourceCategory.ANALYTICS,label="NewsData.io",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your NewsData.io API key to pull news articles into the PostHog Data warehouse.++You can find your API key on your [NewsData.io dashboard](https://newsdata.io/dashboard).++Page size and daily request credits are determined by your NewsData.io plan.""",iconPath="/static/services/newsdata.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/newsdata",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="pub_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked key surfaces as HTTP 401 when `_fetch_page` calls+ # `raise_for_status()`. Retrying can't fix a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://newsdata.io": "Your NewsData.io API key is invalid or has been revoked. Find your key on the NewsData.io dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://newsdata.io": "Your NewsData.io plan does not allow access to this data. Check your plan on the NewsData.io dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: NewsDataSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = NEWSDATA_ENDPOINTS[endpoint]+ # Only date-filter endpoints (archive, crypto) have a genuine server-side timestamp filter.+ has_incremental = endpoint_config.supports_date_filter and bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) 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: NewsDataSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_newsdata_credentials(config.api_key):+ return True, None++ return False, "Invalid NewsData.io API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NewsDataResumeConfig]:+ return ResumableSourceManager[NewsDataResumeConfig](inputs, NewsDataResumeConfig)++ def source_for_pipeline(+ self,+ config: NewsDataSourceConfig,+ resumable_source_manager: ResumableSourceManager[NewsDataResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return newsdata_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.pynew file mode 100644index 000000000000..f175088c7c80--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata.py@@ -0,0 +1,296 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata import newsdata+from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.newsdata import (+ NewsDataError,+ NewsDataResumeConfig,+ _build_query_params,+ _page_url,+ _raise_for_error_body,+ _to_from_date,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.settings import NEWSDATA_ENDPOINTS+++class TestToFromDate:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2024, 1, 15, 12, 34, 56, tzinfo=UTC), "2024-01-15"),+ ("naive_datetime", datetime(2024, 1, 15, 12, 34, 56), "2024-01-15"),+ ("date_value", date(2024, 1, 15), "2024-01-15"),+ ("api_string", "2024-01-15 12:34:56", "2024-01-15"),+ ("none", None, None),+ ]+ )+ def test_to_from_date(self, _name: str, value: Any, expected: str | None) -> None:+ assert _to_from_date(value) == expected+++class TestBuildQueryParams:+ @parameterized.expand(+ [+ # /latest and /sources reject from_date/to_date entirely, so we must never send them —+ # doing so 4xxs the whole sync with UnsupportedParameter.+ ("latest_incremental", "latest", True, datetime(2024, 1, 15, tzinfo=UTC)),+ ("sources_incremental", "sources", True, datetime(2024, 1, 15, tzinfo=UTC)),+ # A date-filter endpoint syncing full-refresh sends no window either.+ ("archive_full_refresh", "archive", False, datetime(2024, 1, 15, tzinfo=UTC)),+ ]+ )+ def test_no_from_date(self, _name: str, endpoint: str, incremental: bool, watermark: Any) -> None:+ params = _build_query_params(NEWSDATA_ENDPOINTS[endpoint], incremental, watermark)+ assert "from_date" not in params++ @parameterized.expand([("archive",), ("crypto",)])+ def test_incremental_uses_watermark_date(self, endpoint: str) -> None:+ params = _build_query_params(NEWSDATA_ENDPOINTS[endpoint], True, datetime(2024, 3, 4, 2, 58, 14, tzinfo=UTC))+ assert params == {"from_date": "2024-03-04"}++ @parameterized.expand([("archive",), ("crypto",)])+ @freeze_time("2026-06-15T12:00:00Z")+ def test_first_sync_applies_lookback_floor(self, endpoint: str) -> None:+ # Without a watermark the first sync must floor at the trailing lookback window instead of+ # crawling the entire (up to 7-year) archive.+ params = _build_query_params(NEWSDATA_ENDPOINTS[endpoint], True, None)+ assert params == {"from_date": "2026-05-16"}+++class TestPageUrl:+ def test_cursor_added_as_page_param(self) -> None:+ url = _page_url(NEWSDATA_ENDPOINTS["latest"], {}, "cursor_token_abc")+ assert url == "https://newsdata.io/api/1/latest?page=cursor_token_abc"++ def test_no_cursor_on_first_page(self) -> None:+ assert _page_url(NEWSDATA_ENDPOINTS["latest"], {}, None) == "https://newsdata.io/api/1/latest"++ def test_query_params_and_cursor_combine(self) -> None:+ url = _page_url(NEWSDATA_ENDPOINTS["archive"], {"from_date": "2024-01-01"}, "tok")+ assert url == "https://newsdata.io/api/1/archive?from_date=2024-01-01&page=tok"++ def test_api_key_never_in_url(self) -> None:+ # The key travels in the X-ACCESS-KEY header, never the URL, so it can't leak into request logs.+ url = _page_url(NEWSDATA_ENDPOINTS["archive"], {"from_date": "2024-01-01"}, "tok")+ assert "apikey" not in url and "ACCESS" not in url+++class TestRaiseForErrorBody:+ def test_error_status_raises(self) -> None:+ # NewsData reports hard failures (unsupported param, quota exhausted) in a 200-body envelope.+ with pytest.raises(NewsDataError):+ _raise_for_error_body(+ {"status": "error", "results": {"message": "quota exceeded", "code": "TooManyRequests"}},+ "https://newsdata.io/api/1/latest",+ )++ def test_success_status_is_noop(self) -> None:+ _raise_for_error_body({"status": "success", "results": []}, "https://newsdata.io/api/1/latest")+++class _FakeResumableManager:+ def __init__(self, state: NewsDataResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[NewsDataResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> NewsDataResumeConfig | None:+ return self._state++ def save_state(self, data: NewsDataResumeConfig) -> None:+ self.saved.append(data)+++def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: dict[str, Any], **kwargs: Any):+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(newsdata, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for batch in get_rows(+ api_key="pub_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestGetRowsPagination:+ def test_follows_next_page_until_absent(self, monkeypatch: Any) -> None:+ pages = {+ "https://newsdata.io/api/1/latest": {+ "status": "success",+ "results": [{"article_id": "a1"}],+ "nextPage": "p2",+ },+ "https://newsdata.io/api/1/latest?page=p2": {+ "status": "success",+ "results": [{"article_id": "a2"}],+ "nextPage": None,+ },+ }+ rows = _collect(_FakeResumableManager(), monkeypatch, "latest", pages)+ assert [r["article_id"] for r in rows] == ["a1", "a2"]++ def test_sources_endpoint_never_paginates(self, monkeypatch: Any) -> None:+ # /sources rejects the `page` param, so even a stray nextPage in the body must not trigger a+ # second request.+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ return {"status": "success", "results": [{"id": "bbc"}], "nextPage": "should_be_ignored"}++ monkeypatch.setattr(newsdata, "_fetch_page", fake_fetch)+ rows = list(+ get_rows(+ api_key="pub_test",+ endpoint="sources",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ assert fetched == ["https://newsdata.io/api/1/sources"]+ assert [r["id"] for batch in rows for r in batch] == ["bbc"]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ pages = {+ "https://newsdata.io/api/1/latest?page=saved_cursor": {+ "status": "success",+ "results": [{"article_id": "a3"}],+ "nextPage": None,+ },+ }+ manager = _FakeResumableManager(NewsDataResumeConfig(next_page="saved_cursor"))+ rows = _collect(manager, monkeypatch, "latest", pages)+ assert [r["article_id"] for r in rows] == ["a3"]++ def test_saves_cursor_after_yielding_batch(self, monkeypatch: Any) -> None:+ # With a tiny batch threshold each page fills a batch, so state is persisted after the yield+ # (never before) — a crash re-yields the last batch rather than skipping ahead.+ monkeypatch.setattr(newsdata, "_BATCH_SIZE", 1)+ pages = {+ "https://newsdata.io/api/1/latest": {+ "status": "success",+ "results": [{"article_id": "a1"}],+ "nextPage": "p2",+ },+ "https://newsdata.io/api/1/latest?page=p2": {+ "status": "success",+ "results": [{"article_id": "a2"}],+ "nextPage": None,+ },+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, "latest", pages)+ # Only the first page has a following page, so exactly one cursor is saved, pointing at it.+ assert [s.next_page for s in manager.saved] == ["p2"]+++def _response_with_status(status_code: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ return response+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 500),+ ("bad_gateway", 502),+ ]+ )+ def test_retryable_status_codes_retry(self, _name: str, status_code: int) -> None:+ throttled = MagicMock()+ throttled.status_code = status_code+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"status": "success", "results": []}++ session = MagicMock()+ session.get.side_effect = [throttled, good]++ with patch.object(newsdata._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = newsdata._fetch_page(session, "https://newsdata.io/api/1/latest", {}, MagicMock())++ assert result == {"status": "success", "results": []}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ("chunked", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ]+ )+ def test_transient_errors_retry(self, _name: str, transient: Exception) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"status": "success", "results": []}++ session = MagicMock()+ session.get.side_effect = [transient, good]++ with patch.object(newsdata._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = newsdata._fetch_page(session, "https://newsdata.io/api/1/latest", {}, MagicMock())++ assert result == {"status": "success", "results": []}+ assert session.get.call_count == 2++ def test_unauthorized_is_not_retried(self) -> None:+ # A 401 is a permanent credential failure: raise_for_status must surface it immediately so+ # get_non_retryable_errors can disable the source, not burn five retries.+ unauthorized = MagicMock()+ unauthorized.status_code = 401+ unauthorized.ok = False+ unauthorized.raise_for_status.side_effect = requests.HTTPError(+ "401 Client Error: Unauthorized", response=_response_with_status(401)+ )++ session = MagicMock()+ session.get.return_value = unauthorized++ with pytest.raises(requests.HTTPError):+ newsdata._fetch_page(session, "https://newsdata.io/api/1/latest", {}, MagicMock())++ assert session.get.call_count == 1+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response++ with patch.object(newsdata, "make_tracked_session", return_value=session):+ assert validate_credentials("pub_test") is expected++ def test_network_failure_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")++ with patch.object(newsdata, "make_tracked_session", return_value=session):+ assert validate_credentials("pub_test") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata_source.pynew file mode 100644index 000000000000..47cd50568a4b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/newsdata/tests/test_newsdata_source.py@@ -0,0 +1,146 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ 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.newsdata.newsdata import NewsDataResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.source import NewsDataSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _source_inputs(**overrides: Any) -> MagicMock:+ inputs = MagicMock()+ inputs.schema_name = overrides.get("schema_name", "archive")+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", True)+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", "2024-01-15 00:00:00")+ return inputs+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert NewsDataSource().source_type == ExternalDataSourceType.NEWSDATA++ def test_config_identity_and_release_contract(self) -> None:+ config = NewsDataSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.NEWS_DATA+ # Alpha but released: the finished source must be reachable, so unreleasedSource stays off.+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ # The doc slug is derived from this URL; a mismatch 404s the docs page.+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/newsdata"++ def test_api_key_is_a_required_secret_field(self) -> None:+ fields = NewsDataSource().get_source_config.fields+ api_key_fields = [f for f in fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"]+ assert len(api_key_fields) == 1+ field = api_key_fields[0]+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+++class TestGetSchemas:+ @parameterized.expand(+ [+ # Only the date-filter endpoints expose a real server-side timestamp filter, so only they+ # can sync incrementally. latest/sources are full refresh.+ ("latest", False),+ ("archive", True),+ ("crypto", True),+ ("sources", False),+ ]+ )+ def test_incremental_support_per_endpoint(self, endpoint: str, expected_incremental: bool) -> None:+ schemas = {s.name: s for s in NewsDataSource().get_schemas(MagicMock(), team_id=1)}+ assert schemas[endpoint].supports_incremental is expected_incremental+ assert schemas[endpoint].supports_append is expected_incremental++ def test_incremental_endpoints_advertise_pubdate(self) -> None:+ schemas = {s.name: s for s in NewsDataSource().get_schemas(MagicMock(), team_id=1)}+ assert [f["field"] for f in schemas["archive"].incremental_fields] == ["pubDate"]++ def test_names_filter(self) -> None:+ schemas = NewsDataSource().get_schemas(MagicMock(), team_id=1, names=["crypto"])+ assert [s.name for s in schemas] == ["crypto"]+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://newsdata.io/api/1/archive?from_date=2024-01-01",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://newsdata.io/api/1/crypto"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ assert any(key in observed for key in NewsDataSource().get_non_retryable_errors())++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='newsdata.io', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://newsdata.io/api/1/latest"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://newsdata.io/api/1/latest"),+ ]+ )+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:+ assert not any(key in observed for key in NewsDataSource().get_non_retryable_errors())+++class TestSourceForPipeline:+ def test_passes_watermark_only_when_incremental(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.source.newsdata_source"+ ) as mock_source:+ NewsDataSource().source_for_pipeline(+ config=MagicMock(api_key="pub_test"),+ resumable_source_manager=MagicMock(),+ inputs=_source_inputs(schema_name="archive", should_use_incremental_field=True),+ )+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "pub_test"+ assert kwargs["endpoint"] == "archive"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-15 00:00:00"++ def test_watermark_dropped_on_full_refresh(self) -> None:+ # On a full-refresh run the stored watermark must not leak into the query, or an unwanted+ # from_date filter would silently truncate the pull.+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.newsdata.source.newsdata_source"+ ) as mock_source:+ NewsDataSource().source_for_pipeline(+ config=MagicMock(api_key="pub_test"),+ resumable_source_manager=MagicMock(),+ inputs=_source_inputs(schema_name="latest", should_use_incremental_field=False),+ )+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = NewsDataSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is NewsDataResumeConfig+++class TestDocumentedTables:+ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O), so the public docs Supported tables section renders.+ source = NewsDataSource()+ assert source.lists_tables_without_credentials is True+ table_names = {t["name"] for t in source.get_documented_tables()}+ assert {"latest", "archive", "crypto", "sources"}.issubset(table_names)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = NewsDataSource().get_canonical_descriptions()+ assert {"latest", "archive", "crypto", "sources"}.issubset(descriptions.keys())