:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add WHO GHO import source (#84462)
Tom Owers98ecd7e141a6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whogho.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whogho.pyindex 121df36e5360..44a72be46819 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whogho.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/whogho.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass WhoGhoSourceConfig(config.Config):- pass+ indicator_codes: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/canonical_descriptions.pynew file mode 100644index 000000000000..13ad8d55549f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/canonical_descriptions.py@@ -0,0 +1,68 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://www.who.int/data/gho/info/gho-odata-api"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "indicators": {+ "description": "Catalog of every health indicator code the Global Health Observatory publishes.",+ "docs_url": _DOCS_URL,+ "columns": {+ "IndicatorCode": "Indicator code, for example WHOSIS_000001. Use this in the source's indicator codes setting.",+ "IndicatorName": "Human readable indicator name.",+ "Language": "Language of the indicator name, for example EN.",+ },+ },+ "dimensions": {+ "description": "Dimensions observations can be disaggregated by, such as country, sex, or age group.",+ "docs_url": _DOCS_URL,+ "columns": {+ "Code": "Dimension code, for example COUNTRY or SEX. Use this to look up rows in dimension_values.",+ "Title": "Human readable dimension name.",+ },+ },+ "dimension_values": {+ "description": "Values for every dimension, such as country codes for the COUNTRY dimension or SEX_MLE / SEX_FMLE for the SEX dimension.",+ "docs_url": _DOCS_URL,+ "columns": {+ "Code": "Value code, referenced by SpatialDim, Dim1, Dim2, and Dim3 on indicator_data rows.",+ "Title": "Human readable name for the value, for example Afghanistan or Male.",+ "Dimension": "Dimension code this value belongs to, matching a row in the dimensions table.",+ "ParentDimension": "Dimension code of the parent grouping, when this value is nested under a broader one.",+ "ParentCode": "Value code of the parent grouping, when this value is nested under a broader one.",+ "ParentTitle": "Human readable name of the parent grouping.",+ },+ },+ "indicator_data": {+ "description": "Observations for every indicator code you configured, one row per country, year, and disaggregation.",+ "docs_url": _DOCS_URL,+ "columns": {+ "Id": "Row identifier, unique within this indicator's own observation set.",+ "IndicatorCode": "Indicator code this observation belongs to, matching a row in the indicators table.",+ "SpatialDimType": "Kind of spatial dimension this observation is reported for, usually COUNTRY.",+ "SpatialDim": "Spatial dimension value code, for example a country code. Look up its name in dimension_values.",+ "ParentLocationCode": "Code of the WHO region the spatial dimension belongs to.",+ "ParentLocation": "Name of the WHO region the spatial dimension belongs to.",+ "TimeDimType": "Kind of time dimension this observation is reported for, usually YEAR.",+ "TimeDim": "Time period as a plain integer, for example a year.",+ "TimeDimensionValue": "Time period as a display string.",+ "TimeDimensionBegin": "Start date of the time period covered by this observation.",+ "TimeDimensionEnd": "End date of the time period covered by this observation.",+ "Dim1Type": "Dimension code for the first disaggregation, when present, such as SEX.",+ "Dim1": "Value code for the first disaggregation. Look up its name in dimension_values.",+ "Dim2Type": "Dimension code for the second disaggregation, when present.",+ "Dim2": "Value code for the second disaggregation.",+ "Dim3Type": "Dimension code for the third disaggregation, when present.",+ "Dim3": "Value code for the third disaggregation.",+ "DataSourceDimType": "Dimension code identifying the underlying data source, when reported.",+ "DataSourceDim": "Value code identifying the underlying data source.",+ "Value": "Display value, sometimes including a confidence interval, for example '48.0 [46.7-49.6]'.",+ "NumericValue": "Observed value as a plain number.",+ "Low": "Lower bound of the confidence interval, when reported.",+ "High": "Upper bound of the confidence interval, when reported.",+ "Comments": "Free text comments on the observation, when present.",+ "Date": "When WHO last refreshed this indicator's whole dataset. Shared by every row for the indicator.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/settings.pynew file mode 100644index 000000000000..3486ad25b070--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/settings.py@@ -0,0 +1,91 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# The API returns the full result set for a request with no default page cap, but $top is+# capped by the server at 1000. Paginate every endpoint at that cap to keep responses bounded --+# some indicators carry hundreds of thousands of observations.+PAGE_SIZE = 1000++INDICATORS_ENDPOINT = "indicators"+DIMENSIONS_ENDPOINT = "dimensions"+DIMENSION_VALUES_ENDPOINT = "dimension_values"+INDICATOR_DATA_ENDPOINT = "indicator_data"++# Querying every configured code walks its full observation history on every refresh, so bound+# the list to keep a single source from consuming worker and storage capacity indefinitely.+MAX_INDICATOR_CODES = 50++# Source-create probes one request per indicator code; cap how many are checked so the form+# stays responsive. Codes beyond the cap still sync -- an unknown one surfaces as a sync error.+MAX_VALIDATED_INDICATOR_CODES = 20+++@dataclass(frozen=True)+class GHOEndpointConfig:+ name: str+ # Path relative to https://ghoapi.azureedge.net/api.+ path: str+ primary_keys: list[str]+ description: str+++CATALOG_ENDPOINTS: dict[str, GHOEndpointConfig] = {+ INDICATORS_ENDPOINT: GHOEndpointConfig(+ name=INDICATORS_ENDPOINT,+ path="/Indicator",+ primary_keys=["IndicatorCode"],+ description="Catalog of every health indicator code the Global Health Observatory publishes.",+ ),+ DIMENSIONS_ENDPOINT: GHOEndpointConfig(+ name=DIMENSIONS_ENDPOINT,+ path="/DIMENSION",+ primary_keys=["Code"],+ description="Dimensions observations can be disaggregated by, such as country, sex, or age group.",+ ),+}++# One shared DIMENSION_VALUE entity backs every dimension's values -- the API declares Code as+# that entity's only key, so it is unique across the whole table. This differs from indicator+# observations below: each indicator code has its own entity type with its own Id sequence, so+# Id alone is only unique within one indicator, not across the indicators merged into one table.+DIMENSION_VALUES_PRIMARY_KEYS = ["Code"]+DIMENSION_VALUES_DESCRIPTION = (+ "Values for every dimension, such as country codes for the COUNTRY dimension "+ "or SEX_MLE / SEX_FMLE for the SEX dimension."+)++INDICATOR_DATA_PRIMARY_KEYS = ["IndicatorCode", "Id"]+INDICATOR_DATA_DESCRIPTION = (+ "Observations for every indicator code you configured, one row per country, year, and disaggregation."+)++ENDPOINTS: tuple[str, ...] = (*CATALOG_ENDPOINTS.keys(), DIMENSION_VALUES_ENDPOINT, INDICATOR_DATA_ENDPOINT)++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ **{name: endpoint.description for name, endpoint in CATALOG_ENDPOINTS.items()},+ DIMENSION_VALUES_ENDPOINT: DIMENSION_VALUES_DESCRIPTION,+ INDICATOR_DATA_ENDPOINT: INDICATOR_DATA_DESCRIPTION,+}++PRIMARY_KEYS: dict[str, list[str]] = {+ **{name: endpoint.primary_keys for name, endpoint in CATALOG_ENDPOINTS.items()},+ DIMENSION_VALUES_ENDPOINT: DIMENSION_VALUES_PRIMARY_KEYS,+ INDICATOR_DATA_ENDPOINT: INDICATOR_DATA_PRIMARY_KEYS,+}++# Every observation row on an indicator carries the same last-modified `Date` (the whole+# indicator's dataset is stamped as one unit whenever WHO republishes it), so filtering on it is+# an all-or-nothing decision per sync: unchanged since last time returns zero rows, changed+# returns the full set again for the merge to upsert. The catalog/reference endpoints have no+# comparable field, so they stay full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ INDICATOR_DATA_ENDPOINT: [+ {+ "label": "Date",+ "type": IncrementalFieldType.DateTime,+ "field": "Date",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/source.pyindex d362a0796f94..d0653356fdd7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/source.py@@ -1,19 +1,49 @@-from typing import cast+from datetime import date, datetime+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.whogho import WhoGhoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.settings import (+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PRIMARY_KEYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.who_gho import (+ WhoGhoResumeConfig,+ parse_indicator_codes,+ validate_credentials as validate_who_gho_credentials,+ who_gho_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WhoGhoSource(SimpleSource[WhoGhoSourceConfig]):+class WhoGhoSource(ResumableSource[WhoGhoSourceConfig, WhoGhoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog -- safe for public docs+ # OData v4, with no version token in the URL, headers, or docs -- the API has never had a+ # second version.+ api_docs_url = "https://www.who.int/data/gho/info/gho-odata-api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WHOGHO@@ -24,7 +54,106 @@ class WhoGhoSource(SimpleSource[WhoGhoSourceConfig]):name=SchemaExternalDataSourceType.WHO_GHO,category=DataWarehouseSourceCategory.ANALYTICS,label="World Health Organization Global Health Observatory (GHO)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["who", "health", "gho", "indicators"],+ caption="""Pull public health statistics from the [WHO Global Health Observatory](https://www.who.int/data/gho) into the PostHog Data warehouse.++The API is open, so no credentials are required. WHO publishes over 2,000 indicator series, which is far too much to sync wholesale, so enter the indicator codes you want, one per line. For example:++```+WHOSIS_000001+WHOSIS_000002+NCD_BMI_30A+```++You can look codes up in the `indicators` table or in the [GHO OData API documentation](https://www.who.int/data/gho/info/gho-odata-api). Observations for every code you enter land in a single `indicator_data` table.++WHO refreshes each indicator on its own publication cycle, typically annually, so a daily or weekly sync is more than enough to pick up changes.""",iconPath="/static/services/who_gho.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/who-gho",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="indicator_codes",+ label="Indicator codes",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="WHOSIS_000001\nWHOSIS_000002\nNCD_BMI_30A",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.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 (404) or a code list that+ # is empty or over the per-source cap -- neither resolves by retrying.+ return {+ "404 Client Error: Not Found for url": "The WHO GHO API did not recognize one of the configured indicator codes. Check the indicator codes on this source.",+ "WHO GHO 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: WhoGhoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)++ def validate_credentials(+ self,+ config: WhoGhoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_who_gho_credentials(parse_indicator_codes(config.indicator_codes))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WhoGhoResumeConfig]:+ return ResumableSourceManager[WhoGhoResumeConfig](inputs, WhoGhoResumeConfig)++ def source_for_pipeline(+ self,+ config: WhoGhoSourceConfig,+ resumable_source_manager: ResumableSourceManager[WhoGhoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint = inputs.schema_name+ indicator_codes = parse_indicator_codes(config.indicator_codes)++ since: Optional[str] = None+ last_value = inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None+ if isinstance(last_value, datetime):+ since = last_value.date().isoformat()+ elif isinstance(last_value, date):+ since = last_value.isoformat()++ return SourceResponse(+ name=endpoint,+ items=lambda: who_gho_source(+ endpoint=endpoint,+ indicator_codes=indicator_codes,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ since=since,+ ),+ 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.+ chunk_size=1,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/tests/test_who_gho.py b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/tests/test_who_gho.pynew file mode 100644index 000000000000..2a65a199465c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/tests/test_who_gho.py@@ -0,0 +1,347 @@+import json+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.who_gho import (+ MAX_INDICATOR_CODES,+ WhoGhoResumeConfig,+ check_indicator_codes,+ parse_indicator_codes,+ validate_credentials,+ who_gho_source,+)++RESOURCE_SESSION_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+WHO_GHO_SESSION_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.who_gho.make_tracked_session"+)+++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://ghoapi.azureedge.net/api/WHOSIS_000001"+ return response+++class TestParseIndicatorCodes:+ @parameterized.expand(+ [+ ("WHOSIS_000001", ["WHOSIS_000001"]),+ ("WHOSIS_000001\nWHOSIS_000002", ["WHOSIS_000001", "WHOSIS_000002"]),+ ("WHOSIS_000001, WHOSIS_000002", ["WHOSIS_000001", "WHOSIS_000002"]),+ ("WHOSIS_000001;WHOSIS_000002", ["WHOSIS_000001", "WHOSIS_000002"]),+ (" WHOSIS_000001 \n\n WHOSIS_000001 ", ["WHOSIS_000001"]),+ ("", []),+ (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 "WHOSIS_000001" in error++ def test_rejects_a_list_over_the_cap(self) -> None:+ 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 TestWhoGhoSourceTransport:+ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ indicator_codes: Optional[list[str]] = None,+ should_use_incremental_field: bool = False,+ since: Optional[str] = None,+ dimension_catalog_responses: Optional[list[Response]] = 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(RESOURCE_SESSION_PATH) as MockResourceSession:+ resource_session = MockResourceSession.return_value+ resource_session.headers = {}+ resource_session.prepare_request.side_effect = lambda request: request+ resource_session.send.side_effect = fake_send++ with patch(WHO_GHO_SESSION_PATH) as MockOwnSession:+ if dimension_catalog_responses is not None:+ MockOwnSession.return_value.get.side_effect = dimension_catalog_responses++ pages = list(+ who_gho_source(+ endpoint=endpoint,+ indicator_codes=indicator_codes or [],+ team_id=123,+ job_id="job-id",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ since=since,+ )+ )++ return sent_params, sent_urls, pages++ def test_catalog_endpoint_paginates_using_skip_and_checkpoints_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ full_page = [{"IndicatorCode": f"CODE{index}"} for index in range(1000)]+ sent_params, sent_urls, pages = self._drive(+ "indicators",+ manager,+ [+ _http_response({"value": full_page}),+ _http_response({"value": []}),+ ],+ )++ # A full page (== $top) means there may be more; a short page below the $top cap is what+ # actually signals the end.+ assert [params["$skip"] for params in sent_params] == [0, 1000]+ assert [params["$top"] for params in sent_params] == [1000, 1000]+ assert sent_urls[0] == "https://ghoapi.azureedge.net/api/Indicator"+ # The empty final page still drives pagination/checkpointing, but the resource wrapper+ # only yields non-empty pages downstream.+ assert pages == [full_page]++ assert [call.args[0] for call in manager.save_state.call_args_list] == [WhoGhoResumeConfig(offset=1000)]+ manager.clear_state.assert_called_once()++ def test_catalog_endpoint_stops_on_a_short_page_without_an_extra_request(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, _, pages = self._drive(+ "dimensions",+ manager,+ [_http_response({"value": [{"Code": "COUNTRY"}]})],+ )++ assert len(sent_params) == 1+ assert pages == [[{"Code": "COUNTRY"}]]+ manager.save_state.assert_not_called()++ def test_catalog_endpoint_resumes_from_the_saved_offset(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = WhoGhoResumeConfig(offset=2000)++ sent_params, _, _ = self._drive("indicators", manager, [_http_response({"value": []})])++ assert sent_params[0]["$skip"] == 2000++ def test_indicator_data_walks_every_configured_code(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, sent_urls, pages = self._drive(+ "indicator_data",+ manager,+ [+ _http_response({"value": [{"IndicatorCode": "WHOSIS_000001", "Id": 1}]}),+ _http_response({"value": [{"IndicatorCode": "WHOSIS_000002", "Id": 2}]}),+ ],+ indicator_codes=["WHOSIS_000001", "WHOSIS_000002"],+ )++ assert sent_urls == [+ "https://ghoapi.azureedge.net/api/WHOSIS_000001",+ "https://ghoapi.azureedge.net/api/WHOSIS_000002",+ ]+ assert [row["IndicatorCode"] for page in pages for row in page] == ["WHOSIS_000001", "WHOSIS_000002"]++ def test_indicator_data_applies_the_date_filter_only_on_an_incremental_sync(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, _, _ = self._drive(+ "indicator_data",+ manager,+ [_http_response({"value": []})],+ indicator_codes=["WHOSIS_000001"],+ should_use_incremental_field=True,+ since="2024-08-02",+ )++ assert sent_params[0]["$filter"] == "date(Date) gt 2024-08-02"++ def test_indicator_data_omits_the_filter_on_a_full_sync(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, _, _ = self._drive(+ "indicator_data",+ manager,+ [_http_response({"value": []})],+ indicator_codes=["WHOSIS_000001"],+ should_use_incremental_field=False,+ since="2024-08-02",+ )++ assert "$filter" not in sent_params[0]++ 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({"value": [{"IndicatorCode": "A", "Id": index} for index in range(1000)]}),+ _http_response({"value": [{"IndicatorCode": "A", "Id": 1001}]}),+ _http_response({"value": [{"IndicatorCode": "B", "Id": 1}]}),+ ],+ indicator_codes=["A", "B"],+ )++ # A full 1000-row page means there may be more, so the mid-code checkpoint carries the+ # next offset; finishing a code moves to the next one so a restart doesn't re-walk it.+ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ WhoGhoResumeConfig(offset=1000, item_index=0),+ WhoGhoResumeConfig(offset=0, item_index=1),+ WhoGhoResumeConfig(offset=0, item_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 = WhoGhoResumeConfig(offset=3000, item_index=1)++ sent_params, sent_urls, _ = self._drive(+ "indicator_data",+ manager,+ [_http_response({"value": [{"IndicatorCode": "B", "Id": 1}]})],+ indicator_codes=["A", "B"],+ )++ assert sent_urls == ["https://ghoapi.azureedge.net/api/B"]+ assert sent_params[0]["$skip"] == 3000++ @parameterized.expand(+ [+ ([],),+ ([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:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with pytest.raises(ValueError, match="WHO GHO source misconfigured"):+ self._drive("indicator_data", manager, [], indicator_codes=indicator_codes)++ manager.load_state.assert_not_called()++ def test_dimension_values_fans_out_over_every_discovered_dimension_code(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, sent_urls, pages = self._drive(+ "dimension_values",+ manager,+ [+ _http_response({"value": [{"Code": "AFG", "Dimension": "COUNTRY"}]}),+ _http_response({"value": [{"Code": "SEX_MLE", "Dimension": "SEX"}]}),+ ],+ dimension_catalog_responses=[_http_response({"value": [{"Code": "COUNTRY"}, {"Code": "SEX"}]})],+ )++ assert sent_urls == [+ "https://ghoapi.azureedge.net/api/DIMENSION/COUNTRY/DimensionValues",+ "https://ghoapi.azureedge.net/api/DIMENSION/SEX/DimensionValues",+ ]+ assert [row["Code"] for page in pages for row in page] == ["AFG", "SEX_MLE"]++ def test_dimension_values_paginates_the_dimension_catalog_discovery_call(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ catalog_page_one = _http_response({"value": [{"Code": f"DIM{index}"} for index in range(1000)]})+ catalog_page_two = _http_response({"value": [{"Code": "LASTDIM"}]})++ _, sent_urls, _ = self._drive(+ "dimension_values",+ manager,+ [_http_response({"value": []}) for _ in range(1001)],+ dimension_catalog_responses=[catalog_page_one, catalog_page_two],+ )++ # One DimensionValues request per discovered code, including the one from the second+ # discovery page, confirms discovery did not stop after the first (full) page.+ assert sent_urls[-1] == "https://ghoapi.azureedge.net/api/DIMENSION/LASTDIM/DimensionValues"+++class TestValidateCredentials:+ def _validate(self, codes: list[str], responses: list[Response]) -> tuple[bool, Optional[str]]:+ with patch(WHO_GHO_SESSION_PATH) as MockSession:+ MockSession.return_value.get.side_effect = responses+ return validate_credentials(codes)++ def test_rejects_an_empty_code_list(self) -> None:+ ok, error = validate_credentials([])++ assert ok is False+ assert error is not None and "WHOSIS_000001" in error++ def test_rejects_a_code_list_over_the_cap_without_probing(self) -> None:+ ok, error = validate_credentials([f"CODE.{index}" for index in range(MAX_INDICATOR_CODES + 1)])++ 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(["WHOSIS_000001"], [_http_response({"value": [{"IndicatorCode": "WHOSIS_000001"}]})])++ assert (ok, error) == (True, None)++ def test_names_the_codes_that_do_not_exist(self) -> None:+ ok, error = self._validate(+ ["WHOSIS_000001", "NOT_A_REAL_CODE"],+ [+ _http_response({"value": [{"IndicatorCode": "WHOSIS_000001"}]}),+ _http_response({}, status_code=404),+ ],+ )++ assert ok is False+ assert error == "These indicator codes were not found: NOT_A_REAL_CODE."++ @parameterized.expand([(500,), (503,), (429,)])+ def test_reports_an_unreachable_api(self, status_code: int) -> None:+ ok, error = self._validate(["WHOSIS_000001"], [_http_response({}, status_code=status_code)])++ assert ok is False+ assert error == "Could not reach the WHO Global Health Observatory API. Please try again."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/tests/test_who_gho_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/tests/test_who_gho_source.pynew file mode 100644index 000000000000..78eb9aca4809--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/tests/test_who_gho_source.py@@ -0,0 +1,207 @@+import datetime+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++import structlog+from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++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.whogho import WhoGhoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.settings import ENDPOINTS, PRIMARY_KEYS+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.source import WhoGhoSource+from products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.who_gho import (+ MAX_INDICATOR_CODES,+ WhoGhoResumeConfig,+ who_gho_source,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(+ schema_name: str = "indicators",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="Date" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestWhoGhoSource:+ def setup_method(self) -> None:+ self.source = WhoGhoSource()+ self.config = WhoGhoSourceConfig(indicator_codes="WHOSIS_000001\nWHOSIS_000002")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.WHOGHO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "WhoGho"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/who-gho"+ assert config.iconPath == "/static/services/who_gho.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_get_schemas(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=123)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ assert all(schema.description for schema in schemas)++ def test_only_indicator_data_supports_incremental(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, team_id=123)}++ assert schemas["indicator_data"].supports_incremental+ assert not schemas["indicators"].supports_incremental+ assert not schemas["dimensions"].supports_incremental+ assert not schemas["dimension_values"].supports_incremental++ 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)++ @parameterized.expand([(endpoint,) for endpoint in 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_includes_the_indicator_code(self) -> None:+ # One table holds observations for every configured indicator, and each indicator has its+ # own Id sequence (a separate OData entity type per code), so the code has to be part of+ # the key or two indicators could overwrite each other's rows.+ assert PRIMARY_KEYS["indicator_data"] == ["IndicatorCode", "Id"]++ def test_dimension_values_primary_key_is_just_code(self) -> None:+ # Unlike indicator_data, every dimension shares one DIMENSION_VALUE entity type, and the+ # API declares Code as that entity's only key -- it is genuinely unique table-wide.+ assert PRIMARY_KEYS["dimension_values"] == ["Code"]++ 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 WhoGhoResumeConfig++ def test_non_retryable_error_matches_an_unknown_indicator_code(self) -> None:+ raised = "404 Client Error: Not Found for url: https://ghoapi.azureedge.net/api/NOT_REAL"++ 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:+ with pytest.raises(ValueError) as excinfo:+ list(+ who_gho_source(+ endpoint="indicator_data",+ indicator_codes=[f"CODE.{index}" for index in range(MAX_INDICATOR_CODES + 1)],+ 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())++ @parameterized.expand([(endpoint,) for endpoint in 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.who_gho.source.who_gho_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"] == ["WHOSIS_000001", "WHOSIS_000002"]++ def test_source_for_pipeline_formats_the_incremental_watermark_as_a_plain_date(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = _make_inputs(+ "indicator_data",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.datetime(2024, 8, 2, 9, 43, 39),+ )++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.source.who_gho_source"+ ) as mock_source:+ mock_source.return_value = iter([])+ response = self.source.source_for_pipeline(self.config, manager, inputs)+ list(cast(Iterable[Any], response.items()))++ assert mock_source.call_args.kwargs["since"] == "2024-08-02"+ assert mock_source.call_args.kwargs["should_use_incremental_field"] is True++ def test_source_for_pipeline_omits_since_on_a_full_sync(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = _make_inputs("indicator_data", should_use_incremental_field=False)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.who_gho.source.who_gho_source"+ ) as mock_source:+ mock_source.return_value = iter([])+ response = self.source.source_for_pipeline(self.config, manager, inputs)+ list(cast(Iterable[Any], response.items()))++ assert mock_source.call_args.kwargs["since"] is None++ @parameterized.expand(+ [+ ("WHOSIS_000001", ["WHOSIS_000001"]),+ ("", []),+ ]+ )+ 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.who_gho.source.validate_who_gho_credentials"+ ) as mock_validate:+ mock_validate.return_value = (True, None)+ self.source.validate_credentials(WhoGhoSourceConfig(indicator_codes=indicator_codes), team_id=123)++ assert mock_validate.call_args.args == (expected_codes,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/who_gho.py b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/who_gho.pynew file mode 100644index 000000000000..4641c1804a57--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/who_gho/who_gho.py@@ -0,0 +1,278 @@+import re+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import quote++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+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.who_gho.settings import (+ CATALOG_ENDPOINTS,+ DIMENSION_VALUES_ENDPOINT,+ DIMENSIONS_ENDPOINT,+ INDICATOR_DATA_ENDPOINT,+ MAX_INDICATOR_CODES,+ MAX_VALIDATED_INDICATOR_CODES,+ PAGE_SIZE,+ GHOEndpointConfig,+)++BASE_URL = "https://ghoapi.azureedge.net/api"++# Codes may be pasted one per line, comma separated, or semicolon separated.+_CODE_SEPARATORS = re.compile(r"[,;\s]+")+++@frozen+class WhoGhoResumeConfig:+ # $skip to resume from within the current resource.+ offset: int = 0+ # Position in the fanned-out list (configured indicator codes, or discovered dimension+ # codes). Only meaningful for indicator_data and dimension_values.+ item_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 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 GHO indicator code, for example WHOSIS_000001."+ 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-checked for changes on every refresh."+ )+ return None+++def _paginator() -> OffsetPaginator:+ # The API has no response field reporting how many rows remain, so pagination stops purely+ # on a short page (fewer rows than $top means the last page).+ return OffsetPaginator(limit=PAGE_SIZE, offset_param="$skip", limit_param="$top", total_path=None)+++def _resource(name: str, path: str, params: dict[str, Any], write_disposition: Any = "replace") -> EndpointResource:+ return {+ "name": name,+ "table_name": name,+ "write_disposition": write_disposition,+ "endpoint": {+ "path": path,+ "data_selector": "value",+ "params": params,+ },+ "table_format": "delta",+ }+++def _rest_config(resource: EndpointResource) -> RESTAPIConfig:+ return {+ # The GHO API is fully open, so there is no auth block to configure.+ "client": {+ "base_url": BASE_URL,+ "paginator": _paginator(),+ },+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [resource],+ }+++def _catalog_pages(+ endpoint: GHOEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WhoGhoResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ initial_paginator_state = {"offset": resume.offset} if resume is not None and resume.offset > 0 else None++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("offset"):+ resumable_source_manager.save_state(WhoGhoResumeConfig(offset=int(state["offset"])))++ yield from rest_api_resource(+ _rest_config(_resource(endpoint.name, endpoint.path, {})),+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def _fetch_all_dimension_codes() -> list[str]:+ """One-off, unpaginated-by-default catalog: fetched fresh at the start of every+ dimension_values sync rather than hardcoded, since WHO adds dimensions over time."""+ session = make_tracked_session()+ codes: list[str] = []+ skip = 0+ while True:+ response = session.get(+ f"{BASE_URL}{CATALOG_ENDPOINTS[DIMENSIONS_ENDPOINT].path}", params={"$top": PAGE_SIZE, "$skip": skip}+ )+ response.raise_for_status()+ rows = response.json().get("value", [])+ codes.extend(row["Code"] for row in rows if row.get("Code"))+ if len(rows) < PAGE_SIZE:+ break+ skip += PAGE_SIZE+ return codes+++def _dimension_values_pages(+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WhoGhoResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ dimension_codes = _fetch_all_dimension_codes()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.item_index if resume is not None else 0+ start_offset = resume.offset if resume is not None else 0++ for index, code in enumerate(dimension_codes):+ if index < start_index:+ continue++ initial_paginator_state = {"offset": start_offset} if index == start_index and start_offset > 0 else None++ def save_checkpoint(state: Optional[dict[str, Any]], code_index: int = index) -> None:+ if state and state.get("offset"):+ resumable_source_manager.save_state(+ WhoGhoResumeConfig(offset=int(state["offset"]), item_index=code_index)+ )+ else:+ # Finished this code's pages: 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(WhoGhoResumeConfig(offset=0, item_index=code_index + 1))++ path = f"/DIMENSION/{quote(code, safe='')}/DimensionValues"+ yield from rest_api_resource(+ _rest_config(_resource(DIMENSION_VALUES_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],+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WhoGhoResumeConfig],+ should_use_incremental_field: bool,+ since: Optional[str],+) -> 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"WHO GHO source misconfigured: {codes_error}")++ write_disposition: Any = (+ {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.item_index if resume is not None else 0+ start_offset = resume.offset if resume is not None else 0++ for index, indicator_code in enumerate(indicator_codes):+ if index < start_index:+ continue++ initial_paginator_state = {"offset": start_offset} if index == start_index and start_offset > 0 else None++ def save_checkpoint(state: Optional[dict[str, Any]], code_index: int = index) -> None:+ if state and state.get("offset"):+ resumable_source_manager.save_state(+ WhoGhoResumeConfig(offset=int(state["offset"]), item_index=code_index)+ )+ else:+ resumable_source_manager.save_state(WhoGhoResumeConfig(offset=0, item_index=code_index + 1))++ params: dict[str, Any] = {}+ if should_use_incremental_field and since is not None:+ # `date()` truncates the comparison to a plain date; the API rejects (or, for the+ # bare property, mishandles) a full ISO datetime-with-offset literal here.+ params["$filter"] = f"date(Date) gt {since}"++ yield from rest_api_resource(+ _rest_config(+ _resource(INDICATOR_DATA_ENDPOINT, f"/{quote(indicator_code, safe='')}", params, write_disposition)+ ),+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def who_gho_source(+ endpoint: str,+ indicator_codes: list[str],+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[WhoGhoResumeConfig],+ should_use_incremental_field: bool = False,+ since: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ if endpoint == INDICATOR_DATA_ENDPOINT:+ yield from _indicator_data_pages(+ indicator_codes, team_id, job_id, resumable_source_manager, should_use_incremental_field, since+ )+ elif endpoint == DIMENSION_VALUES_ENDPOINT:+ yield from _dimension_values_pages(team_id, job_id, resumable_source_manager)+ else:+ yield from _catalog_pages(CATALOG_ENDPOINTS[endpoint], 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]) -> 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++ session = make_tracked_session()+ unknown_codes: list[str] = []++ for indicator_code in indicator_codes[:MAX_VALIDATED_INDICATOR_CODES]:+ response = session.get(f"{BASE_URL}/{quote(indicator_code, safe='')}", params={"$top": 1})+ if response.status_code == 404:+ unknown_codes.append(indicator_code)+ continue+ if response.status_code != 200:+ return False, "Could not reach the WHO Global Health Observatory API. Please try again."++ if unknown_codes:+ return False, f"These indicator codes were not found: {', '.join(unknown_codes)}."++ return True, None