Skip to content

: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.

feat(data-warehouse): add World Bank Open Data source (#77145)

Tom Owersc319ec10fc46
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 91cd48d647d2..98c9d6e3b5c0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -664,6 +664,7 @@ the row lists both.
| workable | HTTP | requests | ✅ |
| workday | HTTP | requests + `rest_source.RESTClient` | ✅ |
| workos | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| world_bank | HTTP | requests + `rest_source.RESTClient` | ✅ |
| wrike | HTTP | requests | ✅ |
| writesonic | HTTP | requests | ✅ |
| wufoo | HTTP | requests | ✅ |
@@ -1417,7 +1418,6 @@ doesn't conflict with concurrent PRs.
- workflowmax
- workiz
- workramp
-- world_bank
- wufoo
- xero
- xsolla
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/worldbank.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/worldbank.py
index 210e55bcc372..c83e60d186b8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/worldbank.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/worldbank.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class WorldBankSourceConfig(config.Config):
- pass
+ indicator_codes: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/canonical_descriptions.py
new file mode 100644
index 000000000000..59e17de518b0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/canonical_descriptions.py
@@ -0,0 +1,107 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://datahelpdesk.worldbank.org/knowledgebase/articles/898581-api-basic-call-structures"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "countries": {
+ "description": "Countries and regional aggregates recognized by the World Bank, with their region, income level, lending type, and capital city.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898590-country-api-queries",
+ "columns": {
+ "id": "ISO 3166-1 alpha-3 country code, or the World Bank's own code for an aggregate.",
+ "iso2Code": "ISO 3166-1 alpha-2 country code.",
+ "name": "Country or aggregate name.",
+ "region": "Geographic region the country belongs to. Aggregates report the region 'Aggregates'.",
+ "adminregion": "Administrative region used for World Bank operational reporting. Empty for high income countries and aggregates.",
+ "incomeLevel": "World Bank income classification, such as high income or lower middle income.",
+ "lendingType": "World Bank lending category, such as IBRD, IDA, blend, or not classified.",
+ "capitalCity": "Capital city. Empty for aggregates.",
+ "longitude": "Longitude of the capital city, as a string.",
+ "latitude": "Latitude of the capital city, as a string.",
+ },
+ },
+ "indicators": {
+ "description": "Catalog of every indicator series the API exposes, with its unit, originating database, and topics.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898599-indicator-api-queries",
+ "columns": {
+ "id": "Indicator code, for example SP.POP.TOTL. Use this in the source's indicator codes setting.",
+ "name": "Human readable indicator name.",
+ "unit": "Unit of measure. Often empty because the unit is described in the name.",
+ "source": "Database the indicator comes from, matching a row in the sources table.",
+ "sourceNote": "Long form description of what the indicator measures and how it is calculated.",
+ "sourceOrganization": "Organization that compiled the underlying data.",
+ "topics": "Subject areas the indicator is filed under, matching rows in the topics table.",
+ },
+ },
+ "sources": {
+ "description": "Databases behind the indicator data, such as World Development Indicators or International Debt Statistics.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Source database identifier. Source 2 is World Development Indicators, the API default.",
+ "lastupdated": "Date the source database was last refreshed, as YYYY-MM-DD.",
+ "name": "Source database name.",
+ "code": "Short code for the source database.",
+ "description": "Description of the source database. Often empty.",
+ "url": "Link to the source database. Often empty.",
+ "dataavailability": "Y when the source exposes data through the API.",
+ "metadataavailability": "Y when the source exposes metadata through the API.",
+ "concepts": "Number of dimensions the source's data is organized by.",
+ },
+ },
+ "topics": {
+ "description": "Subject areas indicators are grouped under, such as Health, Education, or Climate Change.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898611-topic-api-queries",
+ "columns": {
+ "id": "Topic identifier.",
+ "value": "Topic name.",
+ "sourceNote": "Description of what the topic covers.",
+ },
+ },
+ "regions": {
+ "description": "Geographic regions and regional aggregates used to group countries.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898593-region-api-queries",
+ "columns": {
+ "id": "Numeric region identifier. Empty for aggregate regions, so the code is the stable key.",
+ "code": "Region code, for example AFE for Africa Eastern and Southern.",
+ "iso2code": "Two character code for the region.",
+ "name": "Region name.",
+ },
+ },
+ "income_levels": {
+ "description": "World Bank income classifications assigned to countries.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898596-income-level-api-queries",
+ "columns": {
+ "id": "Income level code, for example HIC for high income.",
+ "iso2code": "Two character code for the income level.",
+ "value": "Income level name.",
+ },
+ },
+ "lending_types": {
+ "description": "World Bank lending categories assigned to countries.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898608-lending-type-api-queries",
+ "columns": {
+ "id": "Lending type code, for example IBD for IBRD.",
+ "iso2code": "Two character code for the lending type.",
+ "value": "Lending type name.",
+ },
+ },
+ "indicator_data": {
+ "description": "Observations for every configured indicator code, one row per country and period.",
+ "docs_url": "https://datahelpdesk.worldbank.org/knowledgebase/articles/898599-indicator-api-queries",
+ "columns": {
+ "indicator_id": "Indicator code for this observation, lifted out of the nested indicator object.",
+ "indicator_name": "Indicator name, lifted out of the nested indicator object.",
+ "country_id": "ISO 3166-1 alpha-2 code of the country or aggregate, lifted out of the nested country object.",
+ "country_name": "Country or aggregate name, lifted out of the nested country object.",
+ "countryiso3code": "ISO 3166-1 alpha-3 code of the country or aggregate.",
+ "date": "Period the observation covers: a year (2024), a month (2024M03), or a quarter (2024Q1).",
+ "value": "Observed value, or null when the World Bank has no data for that country and period.",
+ "unit": "Unit of measure for the observation. Usually empty.",
+ "obs_status": "Observation status flag, for example an estimate marker. Usually empty.",
+ "decimal": "Number of decimal places the World Bank recommends when displaying the value.",
+ "indicator": "Original nested object holding the indicator id and name.",
+ "country": "Original nested object holding the country id and name.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/settings.py
new file mode 100644
index 000000000000..028a127c345f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/settings.py
@@ -0,0 +1,84 @@
+from dataclasses import dataclass
+
+# The Indicators API defaults to 50 rows per page and accepts values in the tens of thousands.
+# 1000 keeps the indicator catalog (~30k rows) to ~30 requests without building huge pages.
+PER_PAGE = 1000
+
+# One row per country/period observation for a single indicator. Handled separately from the
+# catalog endpoints below because its path carries a user-supplied indicator code.
+INDICATOR_DATA_ENDPOINT = "indicator_data"
+
+
+@dataclass(frozen=True)
+class WorldBankEndpointConfig:
+ name: str
+ # Path relative to the versioned base URL (e.g. `https://api.worldbank.org/v2`).
+ path: str
+ primary_keys: list[str]
+ description: str
+
+
+CATALOG_ENDPOINTS: dict[str, WorldBankEndpointConfig] = {
+ "countries": WorldBankEndpointConfig(
+ name="countries",
+ path="/country",
+ # `id` is the ISO 3166-1 alpha-3 code (or the World Bank's own code for aggregates).
+ primary_keys=["id"],
+ description="Countries and aggregates, with their region, income level, lending type, and capital city.",
+ ),
+ "indicators": WorldBankEndpointConfig(
+ name="indicators",
+ path="/indicator",
+ primary_keys=["id"],
+ description="Catalog of every indicator series the API exposes, with its unit, source, and topics.",
+ ),
+ "sources": WorldBankEndpointConfig(
+ name="sources",
+ path="/source",
+ primary_keys=["id"],
+ description="Databases the indicator data comes from, such as World Development Indicators.",
+ ),
+ "topics": WorldBankEndpointConfig(
+ name="topics",
+ path="/topic",
+ primary_keys=["id"],
+ description="Subject areas indicators are grouped under, such as Health or Climate Change.",
+ ),
+ "regions": WorldBankEndpointConfig(
+ name="regions",
+ path="/region",
+ # Rows carry an empty `id` for aggregate regions, so `code` is the only stable key.
+ primary_keys=["code"],
+ description="Geographic regions and regional aggregates used to group countries.",
+ ),
+ "income_levels": WorldBankEndpointConfig(
+ name="income_levels",
+ path="/incomeLevel",
+ primary_keys=["id"],
+ description="World Bank income classifications, such as high income or low income.",
+ ),
+ "lending_types": WorldBankEndpointConfig(
+ name="lending_types",
+ path="/lendingType",
+ primary_keys=["id"],
+ description="World Bank lending categories, such as IBRD, IDA, or blend.",
+ ),
+}
+
+# One row per indicator, country, and period, so all three are needed for a table-wide unique key.
+# `indicator_id` and `country_id` are lifted out of the nested objects the API returns.
+INDICATOR_DATA_PRIMARY_KEYS = ["indicator_id", "country_id", "date"]
+
+INDICATOR_DATA_DESCRIPTION = "Observations for every indicator code you configured, one row per country and period."
+
+ENDPOINTS: tuple[str, ...] = (*CATALOG_ENDPOINTS.keys(), INDICATOR_DATA_ENDPOINT)
+
+ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ **{name: endpoint.description for name, endpoint in CATALOG_ENDPOINTS.items()},
+ INDICATOR_DATA_ENDPOINT: INDICATOR_DATA_DESCRIPTION,
+}
+
+PRIMARY_KEYS: dict[str, list[str]] = {
+ **{name: endpoint.primary_keys for name, endpoint in CATALOG_ENDPOINTS.items()},
+ INDICATOR_DATA_ENDPOINT: INDICATOR_DATA_PRIMARY_KEYS,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/source.py
index 185733715c22..e0c4ad548546 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/source.py
@@ -1,21 +1,51 @@
-from typing import cast
+from typing import Optional, cast
from 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.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.worldbank import (
WorldBankSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.settings import (
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ PRIMARY_KEYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.world_bank import (
+ WorldBankResumeConfig,
+ parse_indicator_codes,
+ validate_credentials as validate_world_bank_credentials,
+ world_bank_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class WorldBankSource(SimpleSource[WorldBankSourceConfig]):
+class WorldBankSource(ResumableSource[WorldBankSourceConfig, WorldBankResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # v2 is the only live version; v1 was shut down in June 2020. The version is a path segment
+ # on every request the source makes.
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://datahelpdesk.worldbank.org/knowledgebase/topics/125589-developer-information"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WORLDBANK
@@ -25,8 +55,111 @@ class WorldBankSource(SimpleSource[WorldBankSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.WORLD_BANK,
category=DataWarehouseSourceCategory.ANALYTICS,
- label="World Bank Open Data (Indicators API)",
+ label="World Bank Open Data",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["world bank", "indicators", "gdp", "economic data"],
+ caption="""Pull country-level development statistics from the [World Bank Indicators API](https://datahelpdesk.worldbank.org/knowledgebase/topics/125589-developer-information) into the PostHog Data warehouse.
+
+The API is open, so no credentials are required. The World Bank publishes around 16,000 indicator series, which is far too much to sync wholesale, so enter the indicator codes you want (up to 50), one per line. For example:
+
+```
+SP.POP.TOTL
+NY.GDP.PCAP.CD
+IT.NET.USER.ZS
+```
+
+You can look codes up in the `indicators` table or on [data.worldbank.org](https://data.worldbank.org/indicator). Observations for every code you enter land in a single `indicator_data` table.
+
+The API has no "changed since" filter, and the World Bank revises historical values on each quarterly release, so every table syncs as a full refresh.""",
iconPath="/static/services/world_bank.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/world-bank",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="indicator_codes",
+ label="Indicator codes",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="SP.POP.TOTL\nNY.GDP.PCAP.CD\nIT.NET.USER.ZS",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # The API is unauthenticated, so there are no credential errors. What can permanently
+ # fail a sync is an indicator code the API does not recognize: it answers HTTP 200 with an
+ # error envelope, which the resource's required data selector rejects.
+ return {
+ "Required data_selector '[1]' matched nothing in the response": "The World Bank Indicators API returned an error instead of data. Check that every indicator code you entered is valid.",
+ # A code list that is empty or over the cap can't be fixed by retrying.
+ "World Bank source misconfigured": "Check the indicator codes on this source: the list is empty or has more codes than a single source can sync.",
+ }
+
+ def get_schemas(
+ self,
+ config: WorldBankSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # No endpoint exposes a server-side "changed since" filter, so every table is full
+ # refresh only. The indicator data endpoint does accept a `date=YYYY:YYYY` window, but
+ # the World Bank rewrites historical values on each release, so a windowed sync would
+ # silently miss revisions.
+ return build_endpoint_schemas(ENDPOINTS, {}, names, descriptions=ENDPOINT_DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: WorldBankSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_world_bank_credentials(
+ parse_indicator_codes(config.indicator_codes),
+ self.resolve_api_version(api_version),
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WorldBankResumeConfig]:
+ return ResumableSourceManager[WorldBankResumeConfig](inputs, WorldBankResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: WorldBankSourceConfig,
+ resumable_source_manager: ResumableSourceManager[WorldBankResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ endpoint = inputs.schema_name
+ api_version = self.resolve_api_version(inputs.api_version)
+ indicator_codes = parse_indicator_codes(config.indicator_codes)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: world_bank_source(
+ endpoint=endpoint,
+ indicator_codes=indicator_codes,
+ api_version=api_version,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=PRIMARY_KEYS[endpoint],
+ # The resume checkpoint advances after every yielded page, so each page has to be
+ # durable before the next one moves the bookmark past it. Each yielded item is already
+ # a whole API page, so chunk_size=1 flushes it to Delta on its own rather than letting
+ # several pages sit in the batcher's buffer — a mid-sync failure would otherwise resume
+ # past the buffered pages and finish the full-refresh table with silent gaps.
+ chunk_size=1,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/tests/test_world_bank.py b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/tests/test_world_bank.py
new file mode 100644
index 000000000000..d3cfc846adff
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/tests/test_world_bank.py
@@ -0,0 +1,405 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.world_bank import (
+ DATA_SELECTOR,
+ MAX_INDICATOR_CODES,
+ WorldBankPaginator,
+ WorldBankResumeConfig,
+ check_indicator_codes,
+ flatten_observation,
+ parse_indicator_codes,
+ validate_credentials,
+ world_bank_source,
+)
+
+SESSION_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+
+
+def _payload(rows: Any, pages: Any = 1, page: Any = 1) -> list[Any]:
+ return [{"page": page, "pages": pages, "per_page": "1000", "total": 1}, rows]
+
+
+def _http_response(body: Any, status_code: int = 200) -> Response:
+ response = Response()
+ response.status_code = status_code
+ response._content = json.dumps(body).encode()
+ response.headers["Content-Type"] = "application/json"
+ response.url = "https://api.worldbank.org/v2/country"
+ return response
+
+
+def _meta_response(pages: Any) -> MagicMock:
+ response = MagicMock()
+ response.json.return_value = _payload([{"id": "ABW"}], pages=pages)
+ return response
+
+
+class TestParseIndicatorCodes:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("SP.POP.TOTL", ["SP.POP.TOTL"]),
+ ("SP.POP.TOTL\nNY.GDP.PCAP.CD", ["SP.POP.TOTL", "NY.GDP.PCAP.CD"]),
+ ("SP.POP.TOTL, NY.GDP.PCAP.CD", ["SP.POP.TOTL", "NY.GDP.PCAP.CD"]),
+ ("SP.POP.TOTL;NY.GDP.PCAP.CD", ["SP.POP.TOTL", "NY.GDP.PCAP.CD"]),
+ (" SP.POP.TOTL \n\n SP.POP.TOTL ", ["SP.POP.TOTL"]),
+ ("", []),
+ (None, []),
+ ],
+ )
+ def test_parses_and_deduplicates(self, raw: Optional[str], expected: list[str]) -> None:
+ assert parse_indicator_codes(raw) == expected
+
+
+class TestCheckIndicatorCodes:
+ def test_accepts_a_list_at_the_cap(self) -> None:
+ assert check_indicator_codes([f"CODE.{index}" for index in range(MAX_INDICATOR_CODES)]) is None
+
+ def test_rejects_an_empty_list(self) -> None:
+ error = check_indicator_codes([])
+
+ assert error is not None and "SP.POP.TOTL" in error
+
+ def test_rejects_a_list_over_the_cap(self) -> None:
+ # Each code costs its own full-history walk on every refresh, so an unbounded list would
+ # let one source consume worker, network, and storage capacity indefinitely.
+ codes = [f"CODE.{index}" for index in range(MAX_INDICATOR_CODES + 1)]
+
+ error = check_indicator_codes(codes)
+
+ assert error is not None
+ assert str(MAX_INDICATOR_CODES) in error
+ assert str(len(codes)) in error
+
+
+class TestWorldBankPaginator:
+ @pytest.mark.parametrize(
+ ("pages", "expected_has_next"),
+ [
+ # Catalog endpoints report the page count as a number, others as a string; both have
+ # to stop pagination at the same place.
+ (3, True),
+ ("3", True),
+ (1, False),
+ ("1", False),
+ # An unreadable page count falls back to walking until an empty page.
+ (None, True),
+ ("not-a-number", True),
+ ],
+ )
+ def test_stops_at_the_reported_page_count(self, pages: Any, expected_has_next: bool) -> None:
+ paginator = WorldBankPaginator()
+ paginator.update_state(_meta_response(pages), data=[{"id": "ABW"}])
+
+ assert paginator.page == 2
+ assert paginator.has_next_page is expected_has_next
+
+ @pytest.mark.parametrize("body", [[], [{"page": 1}], "not-json"])
+ def test_falls_back_to_walking_when_the_page_count_is_unreadable(self, body: Any) -> None:
+ # A body with no metadata object, or one the JSON decoder rejects outright, must not
+ # abort pagination — it just costs one extra request to find the end.
+ response = MagicMock()
+ if body == "not-json":
+ response.json.side_effect = ValueError("no JSON object could be decoded")
+ else:
+ response.json.return_value = body
+
+ paginator = WorldBankPaginator()
+ paginator.update_state(response, data=[{"id": "ABW"}])
+
+ assert paginator.has_next_page is True
+
+ def test_str_reports_the_current_page(self) -> None:
+ paginator = WorldBankPaginator(page=7)
+
+ assert str(paginator) == "WorldBankPaginator(page=7)"
+
+ def test_stops_on_empty_page(self) -> None:
+ # Requesting a page past the end answers 200 with an empty row list rather than an error.
+ paginator = WorldBankPaginator()
+ paginator.update_state(_meta_response(99), data=[])
+
+ assert paginator.has_next_page is False
+ assert paginator.get_resume_state() is None
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = WorldBankPaginator()
+ paginator.update_state(_meta_response(5), data=[{"id": "ABW"}])
+ state = paginator.get_resume_state()
+ assert state == {"page": 2}
+
+ resumed = WorldBankPaginator()
+ resumed.set_resume_state(state or {})
+ assert resumed.page == 2
+ assert resumed.has_next_page is True
+
+
+class TestFlattenObservation:
+ def test_lifts_nested_ids_to_the_row_root(self) -> None:
+ # Observations carry no id of their own, so the primary key is built from these.
+ row = flatten_observation(
+ {
+ "indicator": {"id": "SP.POP.TOTL", "value": "Population, total"},
+ "country": {"id": "US", "value": "United States"},
+ "countryiso3code": "USA",
+ "date": "2024",
+ "value": 340003797,
+ }
+ )
+
+ assert row["indicator_id"] == "SP.POP.TOTL"
+ assert row["indicator_name"] == "Population, total"
+ assert row["country_id"] == "US"
+ assert row["country_name"] == "United States"
+ assert row["value"] == 340003797
+
+ def test_tolerates_missing_nested_objects(self) -> None:
+ row = flatten_observation({"date": "2024", "value": None})
+
+ assert row["indicator_id"] is None
+ assert row["country_id"] is None
+
+
+class TestRequiredDataSelector:
+ def test_error_envelope_raises_a_message_the_source_can_classify(self) -> None:
+ # An unknown indicator code comes back as HTTP 200 with an error envelope. The raised
+ # message is what `WorldBankSource.get_non_retryable_errors` matches on, so the two must
+ # stay in step.
+ with pytest.raises(ValueError) as excinfo:
+ RESTClient()._extract_response(
+ [{"message": [{"id": "120", "key": "Invalid value"}]}], DATA_SELECTOR, required=True
+ )
+
+ assert "Required data_selector '[1]' matched nothing in the response" in str(excinfo.value)
+
+ def test_null_row_list_is_a_valid_empty_page(self) -> None:
+ # An indicator with no observations for the requested filter answers `[metadata, null]`.
+ assert RESTClient()._extract_response(_payload(None), DATA_SELECTOR, required=True) == []
+
+
+class TestWorldBankSourceTransport:
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ indicator_codes: Optional[list[str]] = None,
+ ) -> tuple[list[dict[str, Any]], list[str], list[list[dict[str, Any]]]]:
+ sent_params: list[dict[str, Any]] = []
+ sent_urls: list[str] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ sent_urls.append(request.url)
+ return next(response_iter)
+
+ with patch(SESSION_PATH) as MockSession:
+ session = MockSession.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request
+ session.send.side_effect = fake_send
+
+ pages = list(
+ world_bank_source(
+ endpoint=endpoint,
+ indicator_codes=indicator_codes or [],
+ api_version="v2",
+ team_id=123,
+ job_id="job-id",
+ resumable_source_manager=manager,
+ )
+ )
+
+ return sent_params, sent_urls, pages
+
+ def test_catalog_endpoint_paginates_and_checkpoints_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ sent_params, sent_urls, pages = self._drive(
+ "countries",
+ manager,
+ [
+ _http_response(_payload([{"id": "ABW"}], pages=2, page=1)),
+ _http_response(_payload([{"id": "AFG"}], pages=2, page=2)),
+ ],
+ )
+
+ # XML is the API default, so `format=json` has to ride on every request.
+ assert [params["format"] for params in sent_params] == ["json", "json"]
+ assert [params["page"] for params in sent_params] == [1, 2]
+ assert sent_urls[0] == "https://api.worldbank.org/v2/country"
+ assert pages == [[{"id": "ABW"}], [{"id": "AFG"}]]
+
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [WorldBankResumeConfig(page=2)]
+ manager.clear_state.assert_called_once()
+
+ def test_catalog_endpoint_resumes_from_the_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = WorldBankResumeConfig(page=4)
+
+ sent_params, _, _ = self._drive(
+ "indicators", manager, [_http_response(_payload([{"id": "SP.POP.TOTL"}], pages=4, page=4))]
+ )
+
+ assert [params["page"] for params in sent_params] == [4]
+
+ def test_indicator_data_walks_every_code_and_flattens_rows(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ observation = {
+ "indicator": {"id": "SP.POP.TOTL", "value": "Population, total"},
+ "country": {"id": "US", "value": "United States"},
+ "countryiso3code": "USA",
+ "date": "2024",
+ "value": 340003797,
+ }
+ _, sent_urls, pages = self._drive(
+ "indicator_data",
+ manager,
+ [
+ _http_response(_payload([observation])),
+ _http_response(_payload([{**observation, "indicator": {"id": "NY.GDP.PCAP.CD", "value": "GDP"}}])),
+ ],
+ indicator_codes=["SP.POP.TOTL", "NY.GDP.PCAP.CD"],
+ )
+
+ assert sent_urls == [
+ "https://api.worldbank.org/v2/country/all/indicator/SP.POP.TOTL",
+ "https://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.CD",
+ ]
+ assert [row["indicator_id"] for page in pages for row in page] == ["SP.POP.TOTL", "NY.GDP.PCAP.CD"]
+ assert [row["country_id"] for page in pages for row in page] == ["US", "US"]
+
+ def test_indicator_data_checkpoints_the_next_code_when_one_finishes(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ self._drive(
+ "indicator_data",
+ manager,
+ [
+ _http_response(
+ _payload([{"indicator": {"id": "A"}, "country": {"id": "US"}, "date": "2024"}], pages=2)
+ ),
+ _http_response(
+ _payload([{"indicator": {"id": "A"}, "country": {"id": "US"}, "date": "2023"}], pages=2, page=2)
+ ),
+ _http_response(_payload([{"indicator": {"id": "B"}, "country": {"id": "US"}, "date": "2024"}])),
+ ],
+ indicator_codes=["A", "B"],
+ )
+
+ # Mid-code checkpoints carry the next page; finishing a code moves to the next one so a
+ # restart doesn't re-walk codes that already completed.
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ WorldBankResumeConfig(page=2, indicator_index=0),
+ WorldBankResumeConfig(page=1, indicator_index=1),
+ WorldBankResumeConfig(page=1, indicator_index=2),
+ ]
+
+ def test_indicator_data_resume_skips_completed_codes(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = WorldBankResumeConfig(page=3, indicator_index=1)
+
+ sent_params, sent_urls, _ = self._drive(
+ "indicator_data",
+ manager,
+ [_http_response(_payload([{"indicator": {"id": "B"}, "country": {"id": "US"}, "date": "2024"}], pages=3))],
+ indicator_codes=["A", "B"],
+ )
+
+ assert sent_urls == ["https://api.worldbank.org/v2/country/all/indicator/B"]
+ assert [params["page"] for params in sent_params] == [3]
+
+ @pytest.mark.parametrize(
+ "indicator_codes",
+ [[], [f"CODE.{index}" for index in range(MAX_INDICATOR_CODES + 1)]],
+ )
+ def test_indicator_data_refuses_an_out_of_bounds_code_list_before_requesting_anything(
+ self, indicator_codes: list[str]
+ ) -> None:
+ # Validation runs at source-create, but a config saved before the cap existed (or through
+ # anything but the form) would otherwise fan out unbounded on every refresh.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with pytest.raises(ValueError) as excinfo:
+ self._drive("indicator_data", manager, [], indicator_codes=indicator_codes)
+
+ assert "World Bank source misconfigured" in str(excinfo.value)
+ manager.load_state.assert_not_called()
+
+
+class TestValidateCredentials:
+ def _validate(self, codes: list[str], responses: list[Response]) -> tuple[bool, Optional[str]]:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.world_bank.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.side_effect = responses
+ return validate_credentials(codes, "v2")
+
+ def test_rejects_an_empty_code_list(self) -> None:
+ ok, error = validate_credentials([], "v2")
+
+ assert ok is False
+ assert error is not None and "SP.POP.TOTL" in error
+
+ def test_rejects_a_code_list_over_the_cap_without_probing(self) -> None:
+ # The cap has to be enforced at create time, not just at sync time, so an oversized list
+ # can never be saved in the first place.
+ ok, error = validate_credentials([f"CODE.{index}" for index in range(MAX_INDICATOR_CODES + 1)], "v2")
+
+ assert ok is False
+ assert error is not None and str(MAX_INDICATOR_CODES) in error
+
+ def test_accepts_known_codes(self) -> None:
+ ok, error = self._validate(
+ ["SP.POP.TOTL"], [_http_response(_payload([{"id": "SP.POP.TOTL", "name": "Population, total"}]))]
+ )
+
+ assert (ok, error) == (True, None)
+
+ def test_names_the_codes_that_do_not_exist(self) -> None:
+ # An unknown code answers HTTP 200 with a single-element error envelope, so a status check
+ # alone would let it through and the sync would fail later instead.
+ ok, error = self._validate(
+ ["SP.POP.TOTL", "NOT.A.CODE"],
+ [
+ _http_response(_payload([{"id": "SP.POP.TOTL"}])),
+ _http_response([{"message": [{"id": "120", "key": "Invalid value"}]}]),
+ ],
+ )
+
+ assert ok is False
+ assert error == "These indicator codes were not found: NOT.A.CODE."
+
+ @pytest.mark.parametrize("status_code", [403, 429, 500, 503])
+ def test_reports_an_unreachable_api(self, status_code: int) -> None:
+ ok, error = self._validate(["SP.POP.TOTL"], [_http_response([], status_code=status_code)])
+
+ assert ok is False
+ assert error == "Could not reach the World Bank Indicators API. Please try again."
+
+ def test_reports_a_non_json_response(self) -> None:
+ # The World Bank fronts the API with a WAF that answers HTML on a block.
+ html = Response()
+ html.status_code = 200
+ html._content = b"<!DOCTYPE html><html></html>"
+
+ ok, error = self._validate(["SP.POP.TOTL"], [html])
+
+ assert ok is False
+ assert error == "The World Bank Indicators API returned an unexpected response. Please try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/tests/test_world_bank_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/tests/test_world_bank_source.py
new file mode 100644
index 000000000000..cfd216689304
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/tests/test_world_bank_source.py
@@ -0,0 +1,232 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import structlog
+from requests import Response
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.worldbank import (
+ WorldBankSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.settings import ENDPOINTS, PRIMARY_KEYS
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.source import WorldBankSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.world_bank import (
+ MAX_INDICATOR_CODES,
+ WorldBankResumeConfig,
+ world_bank_source,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "countries") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ 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="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestWorldBankSource:
+ def setup_method(self) -> None:
+ self.source = WorldBankSource()
+ self.config = WorldBankSourceConfig(indicator_codes="SP.POP.TOTL\nNY.GDP.PCAP.CD")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.WORLDBANK
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "WorldBank"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/world-bank"
+ assert config.iconPath == "/static/services/world_bank.png"
+ # A finished source ships visible; re-adding the flag would hide it from every user.
+ assert not config.unreleasedSource
+
+ def test_get_source_config_fields(self) -> None:
+ fields = [field for field in self.source.get_source_config.fields if isinstance(field, SourceFieldInputConfig)]
+
+ assert [field.name for field in fields] == ["indicator_codes"]
+ assert fields[0].type == SourceFieldInputConfigType.TEXTAREA
+ assert fields[0].required is True
+ # The API is open, so nothing on this form is a credential.
+ assert fields[0].secret is False
+
+ def test_pinned_version_matches_the_path_the_code_calls(self) -> None:
+ assert self.source.default_version == "v2"
+ assert self.source.supported_versions == ("v2",)
+ assert self.source.resolve_api_version(None) == "v2"
+
+ def test_get_schemas(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=123)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ # No endpoint has a server-side "changed since" filter, so nothing may advertise
+ # incremental or append sync.
+ assert not any(schema.supports_incremental for schema in schemas)
+ assert not any(schema.supports_append for schema in schemas)
+ assert all(schema.description for schema in schemas)
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=123, names=["indicator_data"])
+
+ assert [schema.name for schema in schemas] == ["indicator_data"]
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # The public docs endpoint builds a blank config and calls get_schemas, so discovery must
+ # do no I/O.
+ tables = self.source.get_documented_tables()
+
+ assert [table["name"] for table in tables] == list(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_every_endpoint_has_a_primary_key_and_canonical_descriptions(self, endpoint: str) -> None:
+ assert PRIMARY_KEYS[endpoint]
+ assert CANONICAL_DESCRIPTIONS[endpoint]["columns"]
+
+ def test_indicator_data_primary_key_is_unique_table_wide(self) -> None:
+ # One table holds observations for every configured indicator, so the indicator has to be
+ # part of the key or codes would overwrite each other.
+ assert PRIMARY_KEYS["indicator_data"] == ["indicator_id", "country_id", "date"]
+
+ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is WorldBankResumeConfig
+
+ def test_non_retryable_error_matches_the_required_selector_failure(self) -> None:
+ raised = "Required data_selector '[1]' matched nothing in the response (body keys: list). ..."
+
+ assert error_message_matches(raised, self.source.get_non_retryable_errors().keys())
+
+ def test_non_retryable_error_matches_an_out_of_bounds_code_list(self) -> None:
+ # Retrying an oversized code list just burns the same capacity again, so the sync has to
+ # fail immediately. The raised text and the matched pattern must stay in step.
+ with pytest.raises(ValueError) as excinfo:
+ list(
+ world_bank_source(
+ endpoint="indicator_data",
+ indicator_codes=[f"CODE.{index}" for index in range(MAX_INDICATOR_CODES + 1)],
+ api_version="v2",
+ team_id=123,
+ job_id="job-id",
+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),
+ )
+ )
+
+ assert error_message_matches(str(excinfo.value), self.source.get_non_retryable_errors().keys())
+
+ @pytest.mark.parametrize("endpoint", ENDPOINTS)
+ def test_source_for_pipeline_plumbs_the_endpoint_through(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.source.world_bank_source"
+ ) as mock_source:
+ mock_source.return_value = iter([])
+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs(endpoint))
+ list(cast(Iterable[Any], response.items()))
+
+ assert response.name == endpoint
+ assert response.primary_keys == PRIMARY_KEYS[endpoint]
+ assert mock_source.call_args.kwargs["endpoint"] == endpoint
+ assert mock_source.call_args.kwargs["indicator_codes"] == ["SP.POP.TOTL", "NY.GDP.PCAP.CD"]
+ assert mock_source.call_args.kwargs["api_version"] == "v2"
+
+ def test_a_mid_sync_failure_never_resumes_past_an_unflushed_page(self) -> None:
+ # The resume checkpoint advances after every yielded page, but pages sit in the batcher's
+ # buffer until it flushes. If the checkpoint could move past a buffered page, a failed
+ # request would resume beyond rows that were never written and finish the full-refresh
+ # table with silent gaps. Drive the real batcher at the source's declared chunk size and
+ # fail the third request: pages one and two must be durable and the last saved checkpoint
+ # must point at exactly the page that failed.
+ rest_client = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"
+
+ def _page(rows: list[dict[str, Any]], page: int) -> Response:
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps([{"page": page, "pages": 3, "per_page": "1000", "total": 3}, rows]).encode()
+ response.headers["Content-Type"] = "application/json"
+ response.url = "https://api.worldbank.org/v2/country"
+ return response
+
+ responses: list[Any] = [_page([{"id": "ABW"}], 1), _page([{"id": "AFG"}], 2), RuntimeError("network dropped")]
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ result = next(response_iter)
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs("countries"))
+ # Each yielded item is a whole API page, so one page per batcher chunk is what keeps a page
+ # durable before its checkpoint advances.
+ assert response.chunk_size == 1
+
+ batcher = Batcher(structlog.get_logger(), chunk_size=response.chunk_size)
+ durable_pages: list[Any] = []
+ durable_count_at_checkpoint: list[int] = []
+ manager.save_state.side_effect = lambda _state: durable_count_at_checkpoint.append(len(durable_pages))
+
+ with patch(f"{rest_client}.make_tracked_session") as MockSession:
+ session = MockSession.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request
+ session.send.side_effect = fake_send
+
+ with pytest.raises(RuntimeError, match="network dropped"):
+ for page in cast(Iterable[Any], response.items()):
+ batcher.batch(page)
+ while batcher.should_yield():
+ durable_pages.append(batcher.get_table())
+
+ # Every checkpoint was saved only after that many pages had been flushed durably, and the
+ # last one resumes from page 3 — the request that failed — so nothing durable is skipped.
+ assert durable_count_at_checkpoint == [1, 2]
+ assert [call.args[0].page for call in manager.save_state.call_args_list] == [2, 3]
+ assert len(durable_pages) == 2
+
+ @pytest.mark.parametrize(
+ ("indicator_codes", "expected_codes"),
+ [
+ ("SP.POP.TOTL", ["SP.POP.TOTL"]),
+ ("", []),
+ ],
+ )
+ def test_validate_credentials_parses_the_codes_before_probing(
+ self, indicator_codes: str, expected_codes: list[str]
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.source.validate_world_bank_credentials"
+ ) as mock_validate:
+ mock_validate.return_value = (True, None)
+ self.source.validate_credentials(WorldBankSourceConfig(indicator_codes=indicator_codes), team_id=123)
+
+ assert mock_validate.call_args.args == (expected_codes, "v2")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/world_bank.py b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/world_bank.py
new file mode 100644
index 000000000000..27b03c6def0b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/world_bank/world_bank.py
@@ -0,0 +1,295 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import quote
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.jsonpath_utils import (
+ find_values,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.world_bank.settings import (
+ CATALOG_ENDPOINTS,
+ INDICATOR_DATA_ENDPOINT,
+ PER_PAGE,
+ WorldBankEndpointConfig,
+)
+
+BASE_URL_TEMPLATE = "https://api.worldbank.org/{api_version}"
+
+# Every response is a two-element array: a metadata object followed by the rows. XML is the
+# API default, so `format=json` has to ride on every request for this to hold.
+DATA_SELECTOR = "[1]"
+PAGE_COUNT_PATH = "[0].pages"
+
+# Every configured code costs its own paginated, full-history walk on every refresh (~17k
+# observations, ~17 requests each), so the list has to be bounded or a single source can pull the
+# whole 16,000-series catalog and consume worker, network, and storage capacity indefinitely.
+MAX_INDICATOR_CODES = 50
+
+# Source-create probes one request per indicator code, so cap how many are checked to keep the
+# form responsive. Codes beyond the cap are still synced; a bad one surfaces as a sync error.
+MAX_VALIDATED_INDICATOR_CODES = 20
+
+# Codes may be pasted one per line, comma separated, or semicolon separated (the API's own
+# multi-indicator delimiter).
+_CODE_SEPARATORS = re.compile(r"[,;\s]+")
+
+
+class WorldBankResumeConfig:
+ # Page to resume from, 1-based like the API's own `page` param.
+ page: int = 1
+ # Position in the configured indicator code list. Only meaningful for `indicator_data`,
+ # which walks one paginated request per code.
+ indicator_index: int = 0
+
+
+def parse_indicator_codes(raw: Optional[str]) -> list[str]:
+ codes: list[str] = []
+ for candidate in _CODE_SEPARATORS.split(raw or ""):
+ code = candidate.strip()
+ if code and code not in codes:
+ codes.append(code)
+ return codes
+
+
+def check_indicator_codes(indicator_codes: list[str]) -> Optional[str]:
+ """User-facing error if the configured code list is empty or over the per-source cap.
+
+ Checked both when the source is created and again when a sync starts, so a list that was
+ saved before the cap existed (or through anything but the form) can't fan out unbounded.
+ """
+ if not indicator_codes:
+ return "Enter at least one World Bank indicator code, for example SP.POP.TOTL."
+ if len(indicator_codes) > MAX_INDICATOR_CODES:
+ return (
+ f"Too many indicator codes ({len(indicator_codes)}); enter at most {MAX_INDICATOR_CODES} distinct codes. "
+ "Each code is re-synced in full on every refresh."
+ )
+ return None
+
+
+def _page_count(response: Response) -> Optional[int]:
+ """Total page count from the response metadata object, or None when unreadable.
+
+ Some endpoints (`/source`, `/region`, `/incomeLevel`, `/lendingType`) report it as a string
+ while others report it as a number, so it always goes through int().
+ """
+ try:
+ values = find_values(PAGE_COUNT_PATH, response.json())
+ except Exception:
+ return None
+ if not values:
+ return None
+ try:
+ return int(values[0])
+ except (TypeError, ValueError):
+ return None
+
+
+class WorldBankPaginator(PageNumberPaginator):
+ """1-based `page` / `per_page` pagination driven by the metadata object's page count."""
+
+ def __init__(self, page: int = 1) -> None:
+ super().__init__(base_page=1, page=page, page_param="page")
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data:
+ self._has_next_page = False
+ return
+
+ self.page += 1
+ page_count = _page_count(response)
+ # Requesting a page past the end returns an empty row list rather than an error, so an
+ # unreadable page count just costs one extra request.
+ self._has_next_page = page_count is None or self.page <= page_count
+
+ def __str__(self) -> str:
+ return f"WorldBankPaginator(page={self.page})"
+
+
+def flatten_observation(row: dict[str, Any]) -> dict[str, Any]:
+ """Lift the nested indicator and country ids to the row root.
+
+ Observations carry no id of their own, so the primary key is built from them.
+ """
+ indicator = row.get("indicator") or {}
+ country = row.get("country") or {}
+ return {
+ **row,
+ "indicator_id": indicator.get("id"),
+ "indicator_name": indicator.get("value"),
+ "country_id": country.get("id"),
+ "country_name": country.get("value"),
+ }
+
+
+def _rest_config(api_version: str, resource: EndpointResource) -> RESTAPIConfig:
+ return {
+ # The Indicators API is fully open, so there is no auth block to configure.
+ "client": {
+ "base_url": BASE_URL_TEMPLATE.format(api_version=api_version),
+ "paginator": WorldBankPaginator(),
+ },
+ "resource_defaults": {"write_disposition": "replace"},
+ "resources": [resource],
+ }
+
+
+def _endpoint_resource(name: str, path: str) -> EndpointResource:
+ return {
+ "name": name,
+ "table_name": name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": path,
+ "data_selector": DATA_SELECTOR,
+ # An unknown indicator code or a malformed request comes back as HTTP 200 with a
+ # `[{"message": [...]}]` body, which matches nothing — fail loud instead of
+ # recording an empty table.
+ "data_selector_required": True,
+ "params": {"format": "json", "per_page": PER_PAGE},
+ },
+ "table_format": "delta",
+ }
+
+
+def _indicator_data_resource(indicator_code: str) -> EndpointResource:
+ resource = _endpoint_resource(
+ INDICATOR_DATA_ENDPOINT,
+ f"/country/all/indicator/{quote(indicator_code, safe='')}",
+ )
+ resource["data_map"] = flatten_observation
+ return resource
+
+
+def _catalog_pages(
+ endpoint: WorldBankEndpointConfig,
+ api_version: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[WorldBankResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state = {"page": resume.page} if resume is not None and resume.page > 1 else None
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("page"):
+ resumable_source_manager.save_state(WorldBankResumeConfig(page=int(state["page"])))
+
+ yield from rest_api_resource(
+ _rest_config(api_version, _endpoint_resource(endpoint.name, endpoint.path)),
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def _indicator_data_pages(
+ indicator_codes: list[str],
+ api_version: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[WorldBankResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ # This is the fan-out point: one full paginated walk per code. Refuse an oversized list here
+ # rather than letting a stale config burn capacity indefinitely.
+ codes_error = check_indicator_codes(indicator_codes)
+ if codes_error:
+ raise ValueError(f"World Bank source misconfigured: {codes_error}")
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_index = resume.indicator_index if resume is not None else 0
+ start_page = resume.page if resume is not None else 1
+
+ for index, indicator_code in enumerate(indicator_codes):
+ if index < start_index:
+ continue
+
+ initial_paginator_state = {"page": start_page} if index == start_index and start_page > 1 else None
+
+ def save_checkpoint(state: Optional[dict[str, Any]], code_index: int = index) -> None:
+ if state and state.get("page"):
+ resumable_source_manager.save_state(
+ WorldBankResumeConfig(page=int(state["page"]), indicator_index=code_index)
+ )
+ else:
+ # Last page of this code: point the checkpoint at the start of the next one so a
+ # restart doesn't re-walk codes that already finished.
+ resumable_source_manager.save_state(WorldBankResumeConfig(page=1, indicator_index=code_index + 1))
+
+ yield from rest_api_resource(
+ _rest_config(api_version, _indicator_data_resource(indicator_code)),
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def world_bank_source(
+ endpoint: str,
+ indicator_codes: list[str],
+ api_version: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[WorldBankResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ if endpoint == INDICATOR_DATA_ENDPOINT:
+ yield from _indicator_data_pages(indicator_codes, api_version, team_id, job_id, resumable_source_manager)
+ else:
+ yield from _catalog_pages(CATALOG_ENDPOINTS[endpoint], api_version, team_id, job_id, resumable_source_manager)
+
+ # Walked to completion: drop the checkpoint so a later attempt restarts cleanly instead of
+ # resuming past the end and syncing nothing.
+ resumable_source_manager.clear_state()
+
+
+def validate_credentials(indicator_codes: list[str], api_version: str) -> tuple[bool, Optional[str]]:
+ """Confirm the API is reachable and every configured indicator code resolves to a series."""
+ codes_error = check_indicator_codes(indicator_codes)
+ if codes_error:
+ return False, codes_error
+
+ base_url = BASE_URL_TEMPLATE.format(api_version=api_version)
+ session = make_tracked_session()
+ unknown_codes: list[str] = []
+
+ for indicator_code in indicator_codes[:MAX_VALIDATED_INDICATOR_CODES]:
+ response = session.get(
+ f"{base_url}/indicator/{quote(indicator_code, safe='')}",
+ params={"format": "json", "per_page": "1"},
+ )
+ if response.status_code != 200:
+ return False, "Could not reach the World Bank Indicators API. Please try again."
+
+ try:
+ body = response.json()
+ except ValueError:
+ return False, "The World Bank Indicators API returned an unexpected response. Please try again."
+
+ # A known code returns `[metadata, [series]]`; an unknown one returns a single-element
+ # array carrying an error message.
+ rows = body[1] if isinstance(body, list) and len(body) > 1 else None
+ if not rows:
+ unknown_codes.append(indicator_code)
+
+ if unknown_codes:
+ return False, f"These indicator codes were not found: {', '.join(unknown_codes)}."
+
+ return True, None