: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 gnews import source (#67816)
Tom Owersef368d0d4981
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex da329134715e..d8b9514fdccb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -159,6 +159,7 @@ the row lists both.| giphy | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ || gladly | HTTP | requests | ✅ |+| gnews | HTTP | requests | ✅ || gocardless | HTTP | requests | ✅ || goldcast | HTTP | requests | ✅ || gong | HTTP | requests | ✅ |diff --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 e64754c54ad9..625ad2fa5c4f 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@@ -1295,7 +1295,13 @@ class FullStorySourceConfig(config.Config):@config.configclass GNewsSourceConfig(config.Config):- pass+ api_key: str+ query: str+ category: Literal[+ "general", "world", "nation", "business", "technology", "entertainment", "sports", "science", "health"+ ] = config.value(default="general")+ language: str | None = None+ country: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/canonical_descriptions.pynew file mode 100644index 000000000000..91c49793e5ef--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/canonical_descriptions.py@@ -0,0 +1,33 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Column descriptions taken from the GNews article schema (https://gnews.io/docs/v4). The nested+# `source` object is flattened onto each row (see gnews.py:_flatten_article), so its fields are+# documented here with their `source_` prefix.+_ARTICLE_COLUMNS = {+ "title": "Headline of the article.",+ "description": "Short snippet describing the article.",+ "content": "Main body text of the article (truncated on free plans).",+ "url": "Canonical URL of the article; unique per article and used as the primary key.",+ "image": "URL of the article's main image.",+ "publishedAt": "Publish timestamp of the article in ISO 8601 (UTC).",+ "lang": "Two-letter language code of the article, when a language filter was not applied.",+ "source_id": "Identifier of the publishing source.",+ "source_name": "Name of the publishing source.",+ "source_url": "Homepage URL of the publishing source.",+ "source_country": "Two-letter country code of the publishing source.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "articles": {+ "description": "Worldwide news articles matching the configured keyword search query.",+ "docs_url": "https://gnews.io/docs/v4#search-endpoint",+ "columns": _ARTICLE_COLUMNS,+ },+ "top_headlines": {+ "description": "Breaking news headlines for the configured category.",+ "docs_url": "https://gnews.io/docs/v4#top-headlines-endpoint",+ "columns": _ARTICLE_COLUMNS,+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/gnews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/gnews.pynew file mode 100644index 000000000000..0e8e3d30fefa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/gnews.py@@ -0,0 +1,263 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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.batcher import Batcher+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.gnews.settings import (+ GNEWS_ENDPOINTS,+ MAX_ARTICLES_PER_QUERY,+ PAGE_SIZE,+ GNewsEndpointConfig,+)++GNEWS_BASE_URL = "https://gnews.io/api/v4"++# 1000-article ceiling divided by the page size — the last page we'll ever request for one query.+MAX_PAGES = -(-MAX_ARTICLES_PER_QUERY // PAGE_SIZE)+++class GNewsRetryableError(Exception):+ pass+++class GNewsResumeConfig:+ # The page to re-fetch on resume. Checkpointed as the current (in-flight) page, not the next one,+ # so a crash re-fetches and re-yields it — merge dedupes the overlap on the `url` primary key.+ page_to_refetch: int = 1+++def _get_headers(api_key: str) -> dict[str, str]:+ # Auth via header rather than the `apikey` query param so the key never lands in a logged URL.+ return {"X-Api-Key": api_key, "Accept": "application/json"}+++def _format_from_value(value: Any) -> str | None:+ """Format an incremental cursor as GNews's ISO 8601 `from` filter (`YYYY-MM-DDTHH:MM:SSZ`).++ A future-dated cursor would filter out every article, so cap it at now — asking for articles+ published after now is a no-op and keeps the request valid.+ """+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ dt = min(dt.astimezone(UTC), now)+ elif isinstance(value, date):+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ dt = min(dt, now)+ else:+ return None+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _build_params(+ config: GNewsEndpointConfig,+ query: str | None,+ category: str | None,+ language: str | None,+ country: str | None,+ from_value: str | None,+ page: int,+) -> dict[str, Any]:+ params: dict[str, Any] = {"max": PAGE_SIZE, "sortby": "publishedAt", "page": page}+ if config.path == "/search":+ # /search requires the q keyword param (max 200 chars).+ params["q"] = (query or "")[:200]+ elif category:+ params["category"] = category+ if language:+ params["lang"] = language+ if country:+ params["country"] = country+ if from_value:+ params["from"] = from_value+ return params+++def _build_url(config: GNewsEndpointConfig, params: dict[str, Any]) -> str:+ return f"{GNEWS_BASE_URL}{config.path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type(+ (+ GNewsRetryableError,+ 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, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:+ response = session.get(url, headers=headers, timeout=60)++ # 429 (quota/rate limit) and 5xx are transient; retry with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise GNewsRetryableError(f"GNews API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # Truncate the body so a large or repeated error payload can't flood the logs.+ logger.error(f"GNews API error: status={response.status_code}, body={response.text[:500]!r}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ # Probe /top-headlines (no keyword required) with the smallest possible page. GNews has no+ # per-endpoint scopes, so a single probe confirms the key for every table.+ url = _build_url(GNEWS_ENDPOINTS["top_headlines"], {"category": "general", "max": 1})+ # Redact the key from captured samples/logs (it's sent in a custom X-Api-Key header the+ # name-based denylist may not recognise) and never follow redirects — GNews is a fixed host,+ # so a 30x elsewhere must not replay the credential to another origin.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ try:+ response = session.get(url, headers=_get_headers(api_key), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (400, 401):+ return False, "Invalid GNews API key"+ if response.status_code == 403:+ return False, "Your GNews plan does not permit this request, or its daily request quota is exhausted"+ try:+ errors = response.json().get("errors")+ if errors:+ return False, errors[0] if isinstance(errors, list) else str(errors)+ except (ValueError, TypeError):+ pass+ return False, response.text+++def _flatten_article(item: dict[str, Any]) -> dict[str, Any]:+ """Lift the nested `source` object onto the row so the table has flat columns."""+ source = item.pop("source", None)+ if isinstance(source, dict):+ item["source_id"] = source.get("id")+ item["source_name"] = source.get("name")+ item["source_url"] = source.get("url")+ item["source_country"] = source.get("country")+ return item+++def get_rows(+ api_key: str,+ endpoint: str,+ query: str | None,+ category: str | None,+ language: str | None,+ country: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GNewsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = GNEWS_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # Redact the key from captured samples/logs and never follow redirects — see validate_credentials.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)++ from_value = (+ _format_from_value(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page_to_refetch if resume else 1+ if resume:+ logger.debug(f"GNews: resuming {endpoint} from page {page}")++ while True:+ url = _build_url(config, _build_params(config, query, category, language, country, from_value, page))++ try:+ data = _fetch_page(session, url, headers, logger)+ except requests.HTTPError as exc:+ # GNews rejects pagination beyond page 1 on plans that don't allow it (403). We already+ # have page 1, so stop cleanly rather than failing the whole sync. A 403 on the first+ # page is a genuine quota/permission error and is re-raised.+ if exc.response is not None and exc.response.status_code == 403 and page > 1:+ logger.warning(f"GNews: pagination not available past page {page - 1} on this plan, stopping")+ break+ raise++ articles = data.get("articles", [])+ if not articles:+ break++ # A short page is the last page; MAX_PAGES caps us at the server's 1000-article ceiling.+ is_last_page = len(articles) < PAGE_SIZE or page >= MAX_PAGES+ checkpoint_page = page+ for item in articles:+ batcher.batch(_flatten_article(item))+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields this+ # page instead of skipping it, without pointlessly re-fetching the final page.+ if not is_last_page:+ resumable_source_manager.save_state(GNewsResumeConfig(page_to_refetch=checkpoint_page))++ if is_last_page:+ break+ page += 1++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def gnews_source(+ api_key: str,+ endpoint: str,+ query: str | None,+ category: str | None,+ language: str | None,+ country: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GNewsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = GNEWS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ query=query,+ category=category,+ language=language,+ country=country,+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ # GNews only offers newest-first ordering (sortby=publishedAt), so rows always arrive desc.+ sort_mode="desc",+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/settings.pynew file mode 100644index 000000000000..d805930b996e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/settings.py@@ -0,0 +1,58 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# GNews returns at most 100 articles per request and caps any single query at 1000 articles+# regardless of pagination (https://gnews.io/docs/v4). Page size is the paid-plan maximum;+# free plans silently return fewer, which the paginator handles as a short final page.+PAGE_SIZE = 100+MAX_ARTICLES_PER_QUERY = 1000++# GNews sorts by publish time newest-first when `sortby=publishedAt`; there is no ascending+# option, so every list endpoint emits rows in descending order (see gnews.py).+_PUBLISHED_AT_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "publishedAt",+ "type": IncrementalFieldType.DateTime,+ "field": "publishedAt",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class GNewsEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField]+ # Stable publish timestamp — an article's publishedAt never changes, so it's safe for both+ # the incremental cursor and partitioning.+ partition_key: Optional[str] = "publishedAt"+ sort_mode: Literal["asc", "desc"] = "desc"+ # GNews articles carry no stable id, but a URL uniquely identifies an article across the+ # whole table, so it's the natural primary key for dedup on merge.+ primary_keys: list[str] = field(default_factory=lambda: ["url"])+ should_sync_default: bool = True+++GNEWS_ENDPOINTS: dict[str, GNewsEndpointConfig] = {+ # Keyword search across worldwide sources, driven by the configured `query`.+ "articles": GNewsEndpointConfig(+ name="articles",+ path="/search",+ incremental_fields=_PUBLISHED_AT_INCREMENTAL,+ ),+ # Breaking news for the configured `category` (defaults to general).+ "top_headlines": GNewsEndpointConfig(+ name="top_headlines",+ path="/top-headlines",+ incremental_fields=_PUBLISHED_AT_INCREMENTAL,+ ),+}++ENDPOINTS = tuple(GNEWS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GNEWS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/source.pyindex e8f78d0531b1..825915b854c0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/source.py@@ -1,19 +1,58 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 GNewsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.gnews import (+ GNewsResumeConfig,+ gnews_source,+ validate_credentials as validate_gnews_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.settings import (+ ENDPOINTS,+ GNEWS_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# GNews's fixed set of top-headline categories (https://gnews.io/docs/v4#top-headlines-endpoint).+_CATEGORIES = [+ "general",+ "world",+ "nation",+ "business",+ "technology",+ "entertainment",+ "sports",+ "science",+ "health",+]+@SourceRegistry.register-class GNewsSource(SimpleSource[GNewsSourceConfig]):+class GNewsSource(ResumableSource[GNewsSourceConfig, GNewsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GNEWS@@ -24,7 +63,136 @@ class GNewsSource(SimpleSource[GNewsSourceConfig]):name=SchemaExternalDataSourceType.G_NEWS,category=DataWarehouseSourceCategory.ANALYTICS,label="GNews",- iconPath="/static/services/gnews.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your GNews API key to pull worldwide news articles into the PostHog Data warehouse.++You can find your API key in your [GNews dashboard](https://gnews.io/dashboard).++The **Search query** drives the `articles` table (keyword search), and the **Category** drives the `top_headlines` table. GNews caps every query at 1000 articles, and free plans return fewer results per request with truncated content.""",+ iconPath="/static/services/gnews.png",+ docsUrl="https://posthog.com/docs/cdp/sources/gnews",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="query",+ label="Search query",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="posthog OR analytics",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="category",+ label="Category",+ required=True,+ defaultValue="general",+ options=[+ SourceFieldSelectConfigOption(label=category.capitalize(), value=category)+ for category in _CATEGORIES+ ],+ ),+ SourceFieldInputConfig(+ name="language",+ label="Language (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="en",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="country",+ label="Country (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="us",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or missing key surfaces as an HTTPError 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://gnews.io": "Your GNews API key is invalid. Create a new key in your GNews dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://gnews.io": "Your GNews plan does not permit this request, or its daily request quota is exhausted. Upgrade your plan or reconnect once the quota resets.",+ }++ def get_schemas(+ self,+ config: GNewsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "articles":+ return "Keyword search results for the configured query. Append-only by publish time."+ return "Breaking news for the configured category. Append-only by publish time."++ def _build_schema(endpoint: str) -> SourceSchema:+ return SourceSchema(+ name=endpoint,+ # GNews exposes a genuine server-side `from` filter on publishedAt, so both tables+ # support incremental. There is no updated-record cursor, so they're append-only.+ supports_incremental=True,+ supports_append=True,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=GNEWS_ENDPOINTS[endpoint].should_sync_default,+ description=_description(endpoint),+ )++ 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: GNewsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_gnews_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GNewsResumeConfig]:+ return ResumableSourceManager[GNewsResumeConfig](inputs, GNewsResumeConfig)++ def source_for_pipeline(+ self,+ config: GNewsSourceConfig,+ resumable_source_manager: ResumableSourceManager[GNewsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return gnews_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ query=config.query,+ category=config.category,+ language=config.language,+ country=config.country,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.pynew file mode 100644index 000000000000..d87cd56c3bb4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews.py@@ -0,0 +1,284 @@+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.gnews import gnews+from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.gnews import (+ MAX_PAGES,+ GNewsResumeConfig,+ _build_params,+ _flatten_article,+ _format_from_value,+ get_rows,+ gnews_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.settings import GNEWS_ENDPOINTS, PAGE_SIZE++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gnews.gnews"+++class TestFormatFromValue:+ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime_treated_as_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("non_date_returns_none", "not-a-date", None),+ ("none_returns_none", None, None),+ ]+ )+ def test_format(self, _name: str, value: Any, expected: str | None) -> None:+ with freeze_time("2026-06-01T00:00:00Z"):+ assert _format_from_value(value) == expected++ def test_future_value_capped_to_now(self) -> None:+ # A future cursor would filter out every article; capping keeps the request a valid no-op.+ with freeze_time("2026-06-01T12:00:00Z"):+ assert _format_from_value(datetime(2099, 1, 1, tzinfo=UTC)) == "2026-06-01T12:00:00Z"+++class TestBuildParams:+ def test_search_sends_query_not_category(self) -> None:+ params = _build_params(GNEWS_ENDPOINTS["articles"], "posthog", "technology", None, None, None, 1)+ assert params["q"] == "posthog"+ assert "category" not in params+ assert params["sortby"] == "publishedAt"+ assert params["max"] == PAGE_SIZE++ def test_search_query_truncated_to_200_chars(self) -> None:+ params = _build_params(GNEWS_ENDPOINTS["articles"], "x" * 250, None, None, None, None, 1)+ assert len(params["q"]) == 200++ def test_top_headlines_sends_category_not_query(self) -> None:+ params = _build_params(GNEWS_ENDPOINTS["top_headlines"], "posthog", "business", None, None, None, 2)+ assert params["category"] == "business"+ assert "q" not in params+ assert params["page"] == 2++ def test_optional_filters_and_from_included_when_present(self) -> None:+ params = _build_params(GNEWS_ENDPOINTS["articles"], "posthog", None, "en", "us", "2026-01-01T00:00:00Z", 1)+ assert params["lang"] == "en"+ assert params["country"] == "us"+ assert params["from"] == "2026-01-01T00:00:00Z"++ def test_omitted_optional_filters(self) -> None:+ params = _build_params(GNEWS_ENDPOINTS["articles"], "posthog", None, None, None, None, 1)+ assert "lang" not in params+ assert "country" not in params+ assert "from" not in params+++class TestFlattenArticle:+ def test_source_object_lifted_onto_row(self) -> None:+ row = _flatten_article(+ {+ "title": "t",+ "url": "https://example.com/a",+ "source": {"id": "s1", "name": "Example", "url": "https://example.com", "country": "us"},+ }+ )+ assert "source" not in row+ assert row["source_id"] == "s1"+ assert row["source_name"] == "Example"+ assert row["source_url"] == "https://example.com"+ assert row["source_country"] == "us"+ # The primary key column is untouched.+ assert row["url"] == "https://example.com/a"++ def test_missing_source_is_tolerated(self) -> None:+ row = _flatten_article({"title": "t", "url": "https://example.com/a"})+ assert row == {"title": "t", "url": "https://example.com/a"}+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, {}, True),+ ("bad_key_401", 401, {}, False),+ ("missing_key_400", 400, {}, False),+ ("quota_403", 403, {}, False),+ ("other_error_with_body", 422, {"errors": ["Something went wrong"]}, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, body: dict, expected_valid: bool) -> None:+ response = MagicMock(status_code=status)+ response.json.return_value = body+ session = MagicMock()+ session.get.return_value = response+ with patch(f"{_MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("some-key")+ assert valid is expected_valid+ if not expected_valid:+ assert message++ def test_request_exception_returns_error(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.exceptions.ConnectionError("boom")+ with patch(f"{_MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials("some-key")+ assert valid is False+ assert "boom" in (message or "")+++class TestCredentialHardening:+ # The API key rides in a custom X-Api-Key header, so both call sites must redact it from+ # captured samples/logs and refuse redirects (else a 30x replays the key to another host).+ # These have no observable effect at runtime, so guard the session construction directly.+ def test_validate_credentials_session_is_hardened(self) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=200)+ with patch(f"{_MODULE}.make_tracked_session", return_value=session) as factory:+ validate_credentials("some-key")+ factory.assert_called_once_with(redact_values=("some-key",), allow_redirects=False)++ def test_get_rows_session_is_hardened(self) -> None:+ with patch(f"{_MODULE}.make_tracked_session", return_value=MagicMock()) as factory:+ with patch(f"{_MODULE}._fetch_page", return_value=_page(1)):+ _collect(get_rows("some-key", "articles", "posthog", None, None, None, MagicMock(), _resume_manager()))+ factory.assert_called_once_with(redact_values=("some-key",), allow_redirects=False)+++def _resume_manager(state: GNewsResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = state is not None+ manager.load_state.return_value = state+ return manager+++def _page(num_articles: int, start: int = 0) -> dict:+ return {+ "totalArticles": 9999,+ "articles": [+ {"title": f"a{start + i}", "url": f"https://example.com/{start + i}", "publishedAt": "2026-01-01T00:00:00Z"}+ for i in range(num_articles)+ ],+ }+++def _collect(rows_iter) -> list[dict]:+ out: list[dict] = []+ for table in rows_iter:+ out.extend(table.to_pylist() if hasattr(table, "to_pylist") else table)+ return out+++class TestGetRows:+ def test_stops_on_short_page(self) -> None:+ # A page shorter than PAGE_SIZE is the last page — pagination must stop there.+ pages = [_page(PAGE_SIZE, start=0), _page(3, start=PAGE_SIZE)]+ with patch(f"{_MODULE}._fetch_page", side_effect=pages) as fetch:+ rows = _collect(get_rows("k", "articles", "posthog", None, None, None, MagicMock(), _resume_manager()))+ assert fetch.call_count == 2+ assert len(rows) == PAGE_SIZE + 3+ # source object flattening happened on the way out.+ assert "source" not in rows[0]++ def test_stops_at_max_pages_cap(self) -> None:+ # Every page is full, so only the 1000-article ceiling (MAX_PAGES) halts pagination.+ with patch(f"{_MODULE}._fetch_page", side_effect=lambda *a, **k: _page(PAGE_SIZE)) as fetch:+ _collect(get_rows("k", "articles", "posthog", None, None, None, MagicMock(), _resume_manager()))+ assert fetch.call_count == MAX_PAGES++ def test_resumes_from_saved_page(self) -> None:+ with patch(f"{_MODULE}._fetch_page", return_value=_page(2)):+ with patch(f"{_MODULE}._build_params", wraps=gnews._build_params) as build:+ _collect(+ get_rows(+ "k",+ "articles",+ "posthog",+ None,+ None,+ None,+ MagicMock(),+ _resume_manager(GNewsResumeConfig(page_to_refetch=5)),+ )+ )+ # First (and only, since page 2 rows < PAGE_SIZE) request starts at the saved page.+ assert build.call_args_list[0].args[-1] == 5++ def test_incremental_passes_from_filter(self) -> None:+ with patch(f"{_MODULE}._fetch_page", return_value=_page(1)):+ with patch(f"{_MODULE}._build_params", wraps=gnews._build_params) as build:+ _collect(+ get_rows(+ "k",+ "articles",+ "posthog",+ None,+ None,+ None,+ MagicMock(),+ _resume_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="publishedAt",+ )+ )+ # from_value threaded into the params.+ assert build.call_args_list[0].args[5] == "2026-01-01T00:00:00Z"++ def test_pagination_403_beyond_first_page_stops_gracefully(self) -> None:+ forbidden = requests.HTTPError(response=MagicMock(status_code=403))+ # Page 1 is full (forces a page 2 request); page 2 is a plan-restricted 403.+ with patch(f"{_MODULE}._fetch_page", side_effect=[_page(PAGE_SIZE), forbidden]):+ rows = _collect(get_rows("k", "articles", "posthog", None, None, None, MagicMock(), _resume_manager()))+ # We keep page 1's rows rather than failing the whole sync.+ assert len(rows) == PAGE_SIZE++ def test_403_on_first_page_raises(self) -> None:+ forbidden = requests.HTTPError(response=MagicMock(status_code=403))+ with patch(f"{_MODULE}._fetch_page", side_effect=forbidden):+ with pytest.raises(requests.HTTPError):+ _collect(get_rows("k", "articles", "posthog", None, None, None, MagicMock(), _resume_manager()))+++class _FakeBatcher:+ """Yields after every batched row so the save-state-after-yield contract is observable."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._pending: list[dict] = []++ def batch(self, row: dict) -> None:+ self._pending.append(row)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return bool(self._pending)++ def get_table(self) -> list[dict]:+ out, self._pending = self._pending, []+ return out+++class TestResumableStateSaving:+ def test_state_saved_with_current_page_after_yield(self) -> None:+ manager = _resume_manager()+ # Two full pages then a short page, so page 1 and 2 each checkpoint before advancing.+ pages = [_page(PAGE_SIZE, 0), _page(PAGE_SIZE, PAGE_SIZE), _page(1, 2 * PAGE_SIZE)]+ with patch(f"{_MODULE}.Batcher", _FakeBatcher):+ with patch(f"{_MODULE}._fetch_page", side_effect=pages):+ _collect(get_rows("k", "articles", "posthog", None, None, None, MagicMock(), manager))+ saved_pages = [call.args[0].page_to_refetch for call in manager.save_state.call_args_list]+ # Checkpoints record the page that produced the batch (current page), never a page ahead.+ assert 1 in saved_pages+ assert 2 in saved_pages+ assert max(saved_pages) <= 2+++class TestGnewsSource:+ @parameterized.expand([("articles",), ("top_headlines",)])+ def test_source_response_contract(self, endpoint: str) -> None:+ response = gnews_source("k", endpoint, "posthog", "general", None, None, MagicMock(), _resume_manager())+ assert response.name == endpoint+ assert response.primary_keys == ["url"]+ # GNews only offers newest-first ordering; asc would corrupt the incremental watermark.+ assert response.sort_mode == "desc"+ assert response.partition_keys == ["publishedAt"]+ assert response.partition_mode == "datetime"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews_source.pynew file mode 100644index 000000000000..a7049f217f1d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gnews/tests/test_gnews_source.py@@ -0,0 +1,99 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+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 GNewsSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.gnews import GNewsResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gnews.source import GNewsSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gnews.source"+++def _config(**overrides: Any) -> GNewsSourceConfig:+ defaults: dict[str, Any] = {"api_key": "k", "query": "posthog", "category": "general"}+ defaults.update(overrides)+ return GNewsSourceConfig(**defaults)+++def _inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "articles",+ "schema_id": "sid",+ "source_id": "srcid",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "jid",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestGNewsSource:+ def setup_method(self) -> None:+ self.source = GNewsSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.GNEWS++ def test_get_schemas_are_incremental_and_append_on_published_at(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=1)}+ assert set(schemas) == {"articles", "top_headlines"}+ for schema in schemas.values():+ assert schema.supports_incremental is True+ assert schema.supports_append is True+ assert [f["field"] for f in schema.incremental_fields] == ["publishedAt"]++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=1, names=["top_headlines"])+ assert [s.name for s in schemas] == ["top_headlines"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O, so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True+ assert {t["name"] for t in self.source.get_documented_tables()} == {"articles", "top_headlines"}++ @parameterized.expand([("401 Client Error",), ("403 Client Error",)])+ def test_non_retryable_errors(self, expected_substring: str) -> None:+ assert any(expected_substring in key for key in self.source.get_non_retryable_errors())++ @parameterized.expand([(True, None), (False, "Invalid GNews API key")])+ def test_validate_credentials_delegates(self, valid: bool, message: str | None) -> None:+ with patch(f"{_MODULE}.validate_gnews_credentials", return_value=(valid, message)) as mock_validate:+ result = self.source.validate_credentials(_config(api_key="secret"), team_id=1)+ mock_validate.assert_called_once_with("secret")+ assert result == (valid, message)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GNewsResumeConfig++ def test_source_for_pipeline_plumbs_config_and_schema(self) -> None:+ config = _config(query="analytics", category="technology", language="en", country="us")+ with patch(f"{_MODULE}.gnews_source") as mock_source:+ self.source.source_for_pipeline(config, MagicMock(), _inputs(schema_name="top_headlines"))+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "k"+ assert kwargs["endpoint"] == "top_headlines"+ assert kwargs["query"] == "analytics"+ assert kwargs["category"] == "technology"+ assert kwargs["language"] == "en"+ assert kwargs["country"] == "us"++ def test_source_for_pipeline_suppresses_last_value_when_not_incremental(self) -> None:+ # A stale last-value must not leak into a full-refresh sync.+ inputs = _inputs(should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01T00:00:00Z")+ with patch(f"{_MODULE}.gnews_source") as mock_source:+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None