: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 US Bureau of Economic Analysis (BEA) import source (#84454)
Tom Owers707940d29b95
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/usbea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/usbea.pyindex 67b7b5521f65..77450c26b921 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/usbea.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/usbea.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass UsBeaSourceConfig(config.Config):- pass+ api_key: str+ custom_dataset_name: str | None = None+ custom_query_params: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/canonical_descriptions.pynew file mode 100644index 000000000000..3391dceb2566--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/canonical_descriptions.py@@ -0,0 +1,31 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_REGIONAL_INCOME_COLUMNS = {+ "Code": "BEA statistic code, combining the table name and line code (e.g. SAINC1-3).",+ "GeoFips": "Geographic FIPS code for the area (e.g. a state or county FIPS code).",+ "GeoName": "Human-readable name of the geographic area.",+ "TimePeriod": "Year the statistic applies to.",+ "CL_UNIT": "Unit of measure for the statistic (e.g. Dollars, Persons).",+ "UNIT_MULT": "Base-10 exponent to apply to DataValue (e.g. 3 for thousands, 6 for millions).",+ "DataValue": "The statistic's value, in the unit and multiplier given by CL_UNIT/UNIT_MULT.",+ "NoteRef": "Reference to a footnote in the BEA release describing this or related values.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "StatePersonalIncomeSummary": {+ "description": "BEA Regional dataset, table SAINC1: annual personal income, population, and per capita personal income for every US state.",+ "docs_url": "https://apps.bea.gov/regional/docs/regionalregdata.cfm?param=SAINC1",+ "columns": _REGIONAL_INCOME_COLUMNS,+ },+ "CountyPersonalIncomeSummary": {+ "description": "BEA Regional dataset, table CAINC1: annual personal income, population, and per capita personal income for every US county, for the last 10 years.",+ "docs_url": "https://apps.bea.gov/regional/docs/regionalregdata.cfm?param=CAINC1",+ "columns": _REGIONAL_INCOME_COLUMNS,+ },+ "CustomQuery": {+ "description": "Rows returned by the custom BEA GetData query configured on this source (dataset name and parameters chosen by the user).",+ "docs_url": "https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf",+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/settings.pynew file mode 100644index 000000000000..322bfd9f7c0c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/settings.py@@ -0,0 +1,66 @@+import dataclasses++from products.warehouse_sources.backend.types import IncrementalField++BEA_API_BASE_URL = "https://apps.bea.gov/api/data"++CUSTOM_QUERY_ENDPOINT = "CustomQuery"++# Cheap probe used by validate_credentials: GetParameterList needs only UserID + DatasetName,+# no table/geography/year selection.+VALIDATION_DATASET_NAME = "Regional"++[email protected](frozen=True)+class BeaEndpointConfig:+ dataset_name: str+ """BEA `DatasetName` GetData parameter, e.g. "Regional"."""+ table_name: str+ """BEA `TableName` GetData parameter, e.g. "SAINC1"."""+ line_codes: tuple[str, ...]+ """Documented `LineCode` values for this table. The Regional dataset accepts only one+ LineCode per request (MultipleAcceptedFlag=0), so the transport issues one GetData call+ per code and merges the results."""+ extra_params: dict[str, str]+ """Static GetData params beyond DatasetName/TableName/LineCode, e.g. GeoFips/Year."""+ primary_keys: tuple[str, ...]+++# Both tables and their LineCode values are taken directly from BEA's own API user guide+# examples: SAINC1's GetParameterValuesFiltered example lists LineCode 1/2/3 as personal+# income/population/per capita personal income, and CAINC1's GetData example's PublicTable+# field ("CAINC1 County personal income summary: personal income, population, per capita+# personal income") shows the identical three-statistic layout for the county table.+ENDPOINTS: dict[str, BeaEndpointConfig] = {+ "StatePersonalIncomeSummary": BeaEndpointConfig(+ dataset_name="Regional",+ table_name="SAINC1",+ line_codes=("1", "2", "3"),+ # GeoFips=STATE covers every state plus a handful of BEA regions (~65 geographies),+ # so pairing it with Year=ALL stays well inside BEA's throttling limits.+ extra_params={"GeoFips": "STATE", "Year": "ALL"},+ primary_keys=("Code", "GeoFips", "TimePeriod"),+ ),+ "CountyPersonalIncomeSummary": BeaEndpointConfig(+ dataset_name="Regional",+ table_name="CAINC1",+ line_codes=("1", "2", "3"),+ # BEA advises against combining more than one "all values" wildcard in a request.+ # GeoFips=COUNTY already returns all ~3,100 counties, so Year is capped to the last+ # 10 years rather than ALL to avoid stacking a second wildcard on a multi-decade series.+ extra_params={"GeoFips": "COUNTY", "Year": "LAST10"},+ primary_keys=("Code", "GeoFips", "TimePeriod"),+ ),+}++ENDPOINT_DESCRIPTIONS: dict[str, str] = {+ "StatePersonalIncomeSummary": "SAINC1 State annual personal income summary: personal income, population, per capita personal income, for every US state.",+ "CountyPersonalIncomeSummary": "CAINC1 County personal income summary: personal income, population, per capita personal income, for every US county (last 10 years).",+ CUSTOM_QUERY_ENDPOINT: "Rows returned by the custom BEA GetData query configured on this source (dataset name and parameters chosen by the user).",+}++# BEA has no updated-since filter. The `Year` GetData parameter selects which periods a+# request returns rather than filtering by modification time, and BEA revises recently+# published years on its own release schedule (independent of when we last synced), so every+# table is full refresh.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/source.pyindex a08b3a84a4d1..d9b9c18b1083 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/source.py@@ -1,30 +1,159 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.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.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.usbea import UsBeaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.settings import (+ CUSTOM_QUERY_ENDPOINT,+ ENDPOINT_DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.us_bea import (+ AUTH_ERROR_MESSAGE,+ RESPONSE_TOO_LARGE_ERROR,+ parse_custom_query_params,+ us_bea_source,+ validate_credentials as validate_us_bea_credentials,+ validate_custom_query,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _has_custom_query(config: UsBeaSourceConfig) -> bool:+ return bool((config.custom_dataset_name or "").strip() and (config.custom_query_params or "").strip())++@SourceRegistry.registerclass UsBeaSource(SimpleSource[UsBeaSourceConfig]):+ # Static endpoint catalog with no I/O in get_schemas - safe for public docs.+ lists_tables_without_credentials = True+ # BEA's Data Retrieval API has no version segment or header - the URI and method names+ # documented in the user guide have been stable since the API's release.+ api_docs_url = "https://apps.bea.gov/api/docs/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.USBEA+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ AUTH_ERROR_MESSAGE: "Your BEA UserID is missing or invalid. Register a free UserID at https://apps.bea.gov/api/signup/ and update the source.",+ "BEA custom query": "The custom query on this source is incomplete or invalid. Update the custom query fields on the source and retry.",+ "BEA API rejected the request": "BEA rejected the request. Check the custom query parameters against the API user guide.",+ RESPONSE_TOO_LARGE_ERROR: "The BEA response was too large to process. Narrow the custom query parameters (e.g. a smaller Year range or GeoFips selection) and retry.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: UsBeaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ endpoint_names = list(ENDPOINTS)+ if _has_custom_query(config):+ endpoint_names.append(CUSTOM_QUERY_ENDPOINT)+ return build_endpoint_schemas(endpoint_names, INCREMENTAL_FIELDS, names, descriptions=ENDPOINT_DESCRIPTIONS)++ def validate_credentials(+ self,+ config: UsBeaSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ custom_query_error = validate_custom_query(config.custom_dataset_name, config.custom_query_params)+ if custom_query_error is not None:+ return False, custom_query_error++ return validate_us_bea_credentials(config.api_key)++ def source_for_pipeline(self, config: UsBeaSourceConfig, inputs: SourceInputs) -> SourceResponse:+ if inputs.schema_name == CUSTOM_QUERY_ENDPOINT:+ custom_query_error = validate_custom_query(config.custom_dataset_name, config.custom_query_params)+ if custom_query_error is not None or not _has_custom_query(config):+ raise ValueError(custom_query_error or "BEA custom query is not configured on this source")+ assert config.custom_dataset_name is not None and config.custom_query_params is not None+ return us_bea_source(+ user_id=config.api_key,+ endpoint=CUSTOM_QUERY_ENDPOINT,+ endpoint_config=None,+ custom_dataset_name=config.custom_dataset_name.strip(),+ custom_params=parse_custom_query_params(config.custom_query_params),+ )++ endpoint_config = ENDPOINTS[inputs.schema_name]+ return us_bea_source(+ user_id=config.api_key,+ endpoint=inputs.schema_name,+ endpoint_config=endpoint_config,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.US_BEA,category=DataWarehouseSourceCategory.ANALYTICS,label="US Bureau of Economic Analysis (BEA)",+ keywords=["bea", "gdp", "economic data", "personal income"],+ caption="Sync official US economic statistics from the Bureau of Economic Analysis. Register a free UserID at [apps.bea.gov/api/signup](https://apps.bea.gov/api/signup/). To sync a table beyond the built-in ones, fill in the custom query fields with a BEA dataset name and GetData parameters from the [API user guide](https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf).",+ docsUrl="https://posthog.com/docs/cdp/sources/us-bea",iconPath="/static/services/us_bea.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="UserID",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="custom_dataset_name",+ label="Custom query: dataset name",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="NIPA",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="custom_query_params",+ label="Custom query: parameters",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="TableName=T10101,Frequency=Q,Year=ALL",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/tests/test_us_bea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/tests/test_us_bea.pynew file mode 100644index 000000000000..0bd3d4a977ec--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/tests/test_us_bea.py@@ -0,0 +1,233 @@+import json+from typing import Any, Optional+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.us_bea import (+ UsBeaAuthenticationError,+ UsBeaRequestError,+ UsBeaResponseTooLargeError,+ build_query_url,+ get_data_rows,+ get_endpoint_rows,+ parse_custom_query_params,+ validate_credentials,+ validate_custom_query,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.us_bea"+++def _mock_response(status_code: int = 200, json_data: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = json_data+ # _fetch reads the body via stream=True + iter_content, not response.json()/response.text.+ body = json.dumps(json_data).encode("utf-8") if json_data is not None else b""+ response.iter_content.return_value = iter([body]) if body else iter([])+ return response+++def _patched_session(*responses: MagicMock):+ session = MagicMock()+ session.get.side_effect = list(responses) if len(responses) > 1 else None+ if len(responses) == 1:+ session.get.return_value = responses[0]+ return patch(f"{_MODULE}.make_tracked_session", return_value=session), session+++def _data_payload(rows: list[dict[str, Any]]) -> dict[str, Any]:+ return {"BEAAPI": {"Results": {"Data": rows}}}+++def _error_payload(code: str, description: str) -> dict[str, Any]:+ return {"BEAAPI": {"Results": {"Error": {"APIErrorCode": code, "APIErrorDescription": description}}}}+++class TestUsBea:+ def test_build_query_url_includes_user_id_and_method(self):+ url = build_query_url("secret-id", "GetData", "Regional", {"TableName": "SAINC1"})++ parsed = urlparse(url)+ query = parse_qs(parsed.query)+ assert query["UserID"] == ["secret-id"]+ assert query["method"] == ["GetData"]+ assert query["datasetname"] == ["Regional"]+ assert query["TableName"] == ["SAINC1"]+ assert query["ResultFormat"] == ["JSON"]++ def test_build_query_url_omits_dataset_name_when_not_given(self):+ url = build_query_url("secret-id", "GetDatasetList")++ assert "datasetname" not in parse_qs(urlparse(url).query)++ def test_get_data_rows_returns_data_list(self):+ rows = [{"Code": "SAINC1-1", "GeoFips": "01000", "DataValue": "35706"}]+ response = _mock_response(json_data=_data_payload(rows))+ session = MagicMock()+ session.get.return_value = response++ result = get_data_rows(session, "user-id", "Regional", {"TableName": "SAINC1"})++ assert result == rows++ def test_get_data_rows_handles_single_dict_data_node(self):+ row = {"Code": "SAINC1-1", "GeoFips": "01000"}+ response = _mock_response(json_data={"BEAAPI": {"Results": {"Data": row}}})+ session = MagicMock()+ session.get.return_value = response++ assert get_data_rows(session, "user-id", "Regional", {}) == [row]++ def test_get_data_rows_handles_multi_result_list(self):+ payload = {+ "BEAAPI": {+ "Results": [+ {"Data": [{"Code": "A"}]},+ {"Data": [{"Code": "B"}]},+ ]+ }+ }+ response = _mock_response(json_data=payload)+ session = MagicMock()+ session.get.return_value = response++ assert get_data_rows(session, "user-id", "Regional", {}) == [{"Code": "A"}, {"Code": "B"}]++ def test_get_data_rows_raises_authentication_error_on_invalid_user_id(self):+ response = _mock_response(json_data=_error_payload("1", "Invalid Request - Invalid API UserId."))+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(UsBeaAuthenticationError):+ get_data_rows(session, "bad-id", "Regional", {})++ def test_get_data_rows_raises_request_error_on_other_api_errors(self):+ response = _mock_response(+ json_data=_error_payload(+ "34", "The GetParameterValuesFiltered method has not been implemented on this dataset (coming soon)."+ )+ )+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(UsBeaRequestError):+ get_data_rows(session, "user-id", "Regional", {})++ def test_get_data_rows_raises_when_response_body_exceeds_size_cap(self):+ response = _mock_response(json_data=_data_payload([{"Code": "SAINC1-1"}]))+ response.iter_content.return_value = iter([b"a" * 1024, b"b" * 1024])+ session = MagicMock()+ session.get.return_value = response++ with patch(f"{_MODULE}._MAX_RESPONSE_BYTES", 1500):+ with pytest.raises(UsBeaResponseTooLargeError):+ get_data_rows(session, "user-id", "Regional", {})++ def test_fetch_streams_the_request_instead_of_buffering_it_whole(self):+ response = _mock_response(json_data=_data_payload([{"Code": "SAINC1-1"}]))+ session = MagicMock()+ session.get.return_value = response++ get_data_rows(session, "user-id", "Regional", {})++ assert session.get.call_args.kwargs["stream"] is True+ response.json.assert_not_called()+ response.close.assert_called_once()++ def test_get_endpoint_rows_issues_one_call_per_line_code_and_merges(self):+ endpoint = ENDPOINTS["StatePersonalIncomeSummary"]+ responses = [+ _mock_response(json_data=_data_payload([{"Code": f"SAINC1-{code}"}])) for code in endpoint.line_codes+ ]+ patcher, session = _patched_session(*responses)++ with patcher:+ batches = list(get_endpoint_rows("user-id", endpoint))++ assert session.get.call_count == len(endpoint.line_codes)+ assert [row for batch in batches for row in batch] == [+ {"Code": f"SAINC1-{code}"} for code in endpoint.line_codes+ ]+ requested_line_codes = [+ parse_qs(urlparse(call.args[0]).query)["LineCode"][0] for call in session.get.call_args_list+ ]+ assert requested_line_codes == list(endpoint.line_codes)++ def test_parse_custom_query_params_strips_whitespace_and_ignores_malformed_pairs(self):+ assert parse_custom_query_params(" TableName=T10101 , Frequency=Q ,, garbage ") == {+ "TableName": "T10101",+ "Frequency": "Q",+ }++ @pytest.mark.parametrize(+ ("dataset_name", "params_raw", "expected_fragment"),+ [+ (None, None, None),+ ("", " ", None),+ ("NIPA", "TableName=T10101,Frequency=Q,Year=ALL", None),+ ("NIPA", None, "incomplete"),+ (None, "TableName=T10101", "incomplete"),+ ("NIPA/2", "TableName=T10101", "dataset name is invalid"),+ ("NIPA", ", ,", "parameters are invalid"),+ ],+ )+ def test_validate_custom_query(+ self, dataset_name: Optional[str], params_raw: Optional[str], expected_fragment: Optional[str]+ ):+ error = validate_custom_query(dataset_name, params_raw)++ if expected_fragment is None:+ assert error is None+ else:+ assert error is not None and expected_fragment in error++ def test_validate_credentials_requires_user_id(self):+ valid, error = validate_credentials(" ")++ assert valid is False+ assert error is not None and "missing or invalid" in error++ def test_validate_credentials_success(self):+ response = _mock_response(json_data={"BEAAPI": {"Results": {"Parameter": []}}})+ patcher, _ = _patched_session(response)++ with patcher:+ valid, error = validate_credentials("user-id")++ assert (valid, error) == (True, None)++ def test_validate_credentials_rejects_invalid_user_id(self):+ response = _mock_response(json_data=_error_payload("1", "Invalid Request - Invalid API UserId."))+ patcher, _ = _patched_session(response)++ with patcher:+ valid, error = validate_credentials("bad-id")++ assert valid is False+ assert error is not None and "missing or invalid" in error++ def test_validate_credentials_handles_network_failure(self):+ session = MagicMock()+ session.get.side_effect = ConnectionError("boom")++ with patch(f"{_MODULE}.make_tracked_session", return_value=session):+ valid, error = validate_credentials("user-id")++ assert valid is False+ assert error is not None and "Could not reach" in error++ @pytest.mark.parametrize("endpoint_name", list(ENDPOINTS))+ def test_endpoint_catalog_is_well_formed(self, endpoint_name: str):+ endpoint = ENDPOINTS[endpoint_name]++ assert endpoint.dataset_name+ assert endpoint.table_name+ assert len(endpoint.line_codes) > 0+ assert len(set(endpoint.line_codes)) == len(endpoint.line_codes)+ assert "Year" in endpoint.extra_params+ assert len(endpoint.primary_keys) > 0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/tests/test_us_bea_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/tests/test_us_bea_source.pynew file mode 100644index 000000000000..642fc4225a48--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/tests/test_us_bea_source.py@@ -0,0 +1,137 @@+import pytest+from unittest.mock import patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.usbea import UsBeaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.settings import (+ CUSTOM_QUERY_ENDPOINT,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.source import UsBeaSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(**overrides) -> UsBeaSourceConfig:+ return UsBeaSourceConfig(api_key="test-user-id", **overrides)+++def _custom_config() -> UsBeaSourceConfig:+ return _config(custom_dataset_name="NIPA", custom_query_params="TableName=T10101,Frequency=Q,Year=ALL")+++class _FakeInputs:+ def __init__(self, schema_name: str) -> None:+ self.schema_name = schema_name+++class TestUsBeaSource:+ def setup_method(self):+ self.source = UsBeaSource()++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.USBEA++ def test_source_config_is_released_alpha(self):+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/us-bea"+ assert config.category is not None++ def test_source_config_fields(self):+ fields = {field.name: field for field in self.source.get_source_config.fields}++ api_key_field = fields["api_key"]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+ for name in ("custom_dataset_name", "custom_query_params"):+ custom_field = fields[name]+ assert isinstance(custom_field, SourceFieldInputConfig)+ assert custom_field.required is False++ def test_get_schemas_static_catalog(self):+ schemas = self.source.get_schemas(_config(), team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ assert all(schema.supports_incremental is False for schema in schemas)+ assert all(schema.supports_append is False for schema in schemas)+ assert all(schema.description for schema in schemas)++ def test_get_schemas_includes_custom_query_when_configured(self):+ schemas = self.source.get_schemas(_custom_config(), team_id=1)++ assert [schema.name for schema in schemas] == [*ENDPOINTS, CUSTOM_QUERY_ENDPOINT]++ def test_get_schemas_names_filter(self):+ schemas = self.source.get_schemas(_config(), team_id=1, names=["StatePersonalIncomeSummary"])++ assert [schema.name for schema in schemas] == ["StatePersonalIncomeSummary"]++ @pytest.mark.parametrize(+ "overrides",+ [+ {"custom_dataset_name": "NIPA"},+ {"custom_dataset_name": "NIPA", "custom_query_params": ""},+ {"custom_query_params": "TableName=T10101"},+ ],+ )+ def test_validate_credentials_rejects_partial_custom_query(self, overrides):+ valid, error = self.source.validate_credentials(_config(**overrides), team_id=1)++ assert valid is False+ assert error is not None and "incomplete" in error++ def test_validate_credentials_delegates_to_transport(self):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.source.validate_us_bea_credentials",+ return_value=(True, None),+ ) as mock_validate:+ valid, error = self.source.validate_credentials(_config(), team_id=1)++ assert (valid, error) == (True, None)+ mock_validate.assert_called_once_with("test-user-id")++ @pytest.mark.parametrize("endpoint_name", list(ENDPOINTS))+ def test_source_for_pipeline_builds_catalog_endpoint(self, endpoint_name):+ response = self.source.source_for_pipeline(_config(), _FakeInputs(endpoint_name)) # type: ignore[arg-type]++ assert response.name == endpoint_name+ assert response.primary_keys == list(ENDPOINTS[endpoint_name].primary_keys)++ def test_source_for_pipeline_custom_query_plumbing(self):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.source.us_bea_source"+ ) as mock_source:+ self.source.source_for_pipeline(_custom_config(), _FakeInputs(CUSTOM_QUERY_ENDPOINT)) # type: ignore[arg-type]++ kwargs = mock_source.call_args.kwargs+ assert kwargs["custom_dataset_name"] == "NIPA"+ assert kwargs["custom_params"] == {"TableName": "T10101", "Frequency": "Q", "Year": "ALL"}+ assert kwargs["endpoint_config"] is None++ def test_source_for_pipeline_custom_query_unconfigured_raises(self):+ with pytest.raises(ValueError, match="BEA custom query"):+ self.source.source_for_pipeline(_config(), _FakeInputs(CUSTOM_QUERY_ENDPOINT)) # type: ignore[arg-type]++ @pytest.mark.parametrize(+ "error_message",+ [+ "BEA UserID is missing or invalid. Register a free UserID at https://apps.bea.gov/api/signup/",+ "BEA custom query is incomplete: set both the dataset name and the query parameters",+ "BEA API rejected the request: Invalid TableName",+ ],+ )+ def test_known_permanent_failures_are_non_retryable(self, error_message):+ non_retryable = self.source.get_non_retryable_errors()++ assert any(pattern in error_message for pattern in non_retryable)++ def test_canonical_descriptions_cover_catalog_endpoints(self):+ descriptions = self.source.get_canonical_descriptions()++ for endpoint_name in ENDPOINTS:+ assert endpoint_name in descriptions+ assert descriptions[endpoint_name].get("description")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/us_bea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/us_bea.pynew file mode 100644index 000000000000..80806ad9cc0a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/us_bea/us_bea.py@@ -0,0 +1,256 @@+import re+import json+from collections.abc import Iterator, Mapping+from typing import Any, Optional+from urllib.parse import urlencode++from requests import Response, Session++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.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.us_bea.settings import (+ BEA_API_BASE_URL,+ VALIDATION_DATASET_NAME,+ BeaEndpointConfig,+)++_REQUEST_TIMEOUT = 120++# Rows per yielded chunk. GetData responses aren't paginated (BEA returns the whole+# requested slice in one call), so this only bounds the size of each batch handed to the+# pipeline's batcher.+_ROWS_PER_CHUNK = 5000++# GetData isn't paginated, so a broad custom query (e.g. GeoFips=STATE with Year=ALL across a+# large dataset) can return a very large single body. requests buffers the whole response into+# memory by default and json.loads then duplicates it while parsing, so stream the body and cap+# what's read into memory instead of trusting the request to stay small. Generous enough for any+# documented BEA regional/national table.+_MAX_RESPONSE_BYTES = 128 * 1024 * 1024+_RESPONSE_CHUNK_BYTES = 256 * 1024++AUTH_ERROR_MESSAGE = "BEA UserID is missing or invalid"+REQUEST_ERROR_PREFIX = "BEA API rejected the request"+RESPONSE_SHAPE_ERROR_PREFIX = "Unexpected response from the BEA API"+RESPONSE_TOO_LARGE_ERROR = "BEA API response body was too large"++# BEA dataset names are a single alphanumeric token (NIPA, Regional, ITA, GDPbyIndustry, ...).+_DATASET_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")+++class UsBeaApiError(Exception):+ pass+++class UsBeaAuthenticationError(UsBeaApiError):+ pass+++class UsBeaRequestError(UsBeaApiError):+ """A rejected request that retrying cannot fix - an unknown table, geography, or year."""+++class UsBeaResponseTooLargeError(UsBeaApiError):+ """Non-retryable: re-issuing the same query returns the same oversized body."""+++def build_query_url(+ user_id: str, method: str, dataset_name: Optional[str] = None, params: Optional[Mapping[str, str]] = None+) -> str:+ query: dict[str, str] = {"UserID": user_id, "method": method, "ResultFormat": "JSON"}+ if dataset_name is not None:+ query["datasetname"] = dataset_name+ if params:+ query.update(params)+ return f"{BEA_API_BASE_URL}?{urlencode(query)}"+++def parse_custom_query_params(raw: str) -> dict[str, str]:+ """Parse the source's freeform "Key=Value,Key=Value" custom query params field."""+ params: dict[str, str] = {}+ for pair in raw.split(","):+ cleaned = pair.strip()+ if "=" not in cleaned:+ continue+ key, _, value = cleaned.partition("=")+ key = key.strip()+ if key:+ params[key] = value.strip()+ return params+++def validate_custom_query(dataset_name: Optional[str], params_raw: Optional[str]) -> str | None:+ """Validate the custom query config fields; returns a user-facing error message or None."""+ values = (dataset_name or "", params_raw or "")+ if not any(value.strip() for value in values):+ return None+ if not all(value.strip() for value in values):+ return "BEA custom query is incomplete: set both the dataset name and the query parameters"+ assert dataset_name is not None and params_raw is not None+ if not _DATASET_NAME_RE.match(dataset_name.strip()):+ return "BEA custom query dataset name is invalid. Use a BEA DatasetName like NIPA, Regional, or ITA."+ if not parse_custom_query_params(params_raw):+ return (+ "BEA custom query parameters are invalid. Use a comma-separated list like "+ "TableName=T10101,Frequency=Q,Year=ALL"+ )+ return None+++def _results_list(payload: Any) -> list[dict[str, Any]]:+ """BEA nests results under BEAAPI.Results, a dict normally but a list when a request+ spans multiple result sets (e.g. a dataset that accepts multiple TableNames)."""+ try:+ results = payload["BEAAPI"]["Results"]+ except (KeyError, TypeError):+ return []+ if isinstance(results, list):+ return [result for result in results if isinstance(result, dict)]+ if isinstance(results, dict):+ return [results]+ return []+++def _extract_error(payload: Any) -> Optional[str]:+ for result in _results_list(payload):+ error = result.get("Error")+ if isinstance(error, list):+ error = error[0] if error else None+ if isinstance(error, dict):+ return str(error.get("APIErrorDescription") or "BEA API error")+ return None+++def _extract_rows(payload: Any) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for result in _results_list(payload):+ data = result.get("Data")+ if data is None:+ continue+ data_list = data if isinstance(data, list) else [data]+ rows.extend(row for row in data_list if isinstance(row, dict))+ return rows+++def _raise_for_error(response: Response, payload: Any) -> None:+ # BEA reports invalid credentials and bad parameters as HTTP 200 with an Error node in+ # the body, not via the HTTP status - only throttling (429) is a real status-code error.+ description = _extract_error(payload)+ if description is not None:+ if "userid" in description.lower():+ raise UsBeaAuthenticationError(f"{AUTH_ERROR_MESSAGE}: {description}")+ raise UsBeaRequestError(f"{REQUEST_ERROR_PREFIX}: {description}")+ if not response.ok:+ raise UsBeaApiError(f"BEA API error: status={response.status_code}")+++def _read_capped_body(response: Response, max_bytes: Optional[int] = None) -> bytes:+ """Read a streamed response body into memory, aborting past `max_bytes`.++ Called on a response opened with `stream=True` so nothing is buffered until here.++ `max_bytes` defaults to the module-level `_MAX_RESPONSE_BYTES`, looked up at call time+ (not bound as a default argument value) so tests can patch it.+ """+ if max_bytes is None:+ max_bytes = _MAX_RESPONSE_BYTES+ chunks: list[bytes] = []+ total = 0+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if not chunk:+ continue+ total += len(chunk)+ if total > max_bytes:+ raise UsBeaResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+++def _fetch(session: Session, url: str) -> dict[str, Any]:+ response = session.get(url, timeout=_REQUEST_TIMEOUT, stream=True)+ try:+ body = _read_capped_body(response)+ try:+ payload = json.loads(body)+ except ValueError as e:+ if not response.ok:+ raise UsBeaApiError(f"BEA API error: status={response.status_code}") from e+ raise ValueError(f"{RESPONSE_SHAPE_ERROR_PREFIX}: body is not valid JSON") from e+ finally:+ response.close()+ _raise_for_error(response, payload)+ if not isinstance(payload, dict):+ raise ValueError(f"{RESPONSE_SHAPE_ERROR_PREFIX}: expected a JSON object")+ return payload+++def get_data_rows(session: Session, user_id: str, dataset_name: str, params: Mapping[str, str]) -> list[dict[str, Any]]:+ url = build_query_url(user_id, "GetData", dataset_name, params)+ return _extract_rows(_fetch(session, url))+++def get_endpoint_rows(user_id: str, endpoint: BeaEndpointConfig) -> Iterator[list[dict[str, Any]]]:+ """One GetData call per documented LineCode, merged into a single stream.++ Each row already carries a `Code` field like "SAINC1-3" that embeds the table and line+ code, so rows from different LineCode calls never collide on primary key.+ """+ session = make_tracked_session(redact_values=(user_id,))+ for line_code in endpoint.line_codes:+ params = {"TableName": endpoint.table_name, "LineCode": line_code, **endpoint.extra_params}+ rows = get_data_rows(session, user_id, endpoint.dataset_name, params)+ for start in range(0, len(rows), _ROWS_PER_CHUNK):+ yield rows[start : start + _ROWS_PER_CHUNK]+++def get_custom_query_rows(user_id: str, dataset_name: str, params: Mapping[str, str]) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(redact_values=(user_id,))+ rows = get_data_rows(session, user_id, dataset_name, params)+ for start in range(0, len(rows), _ROWS_PER_CHUNK):+ yield rows[start : start + _ROWS_PER_CHUNK]+++def us_bea_source(+ user_id: str,+ endpoint: str,+ endpoint_config: Optional[BeaEndpointConfig],+ custom_dataset_name: Optional[str] = None,+ custom_params: Optional[Mapping[str, str]] = None,+) -> SourceResponse:+ if endpoint_config is not None:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_endpoint_rows(user_id, endpoint_config),+ primary_keys=list(endpoint_config.primary_keys),+ )++ assert custom_dataset_name is not None and custom_params is not None+ return SourceResponse(+ name=endpoint,+ # The geography/dimension columns of an arbitrary custom query aren't known ahead of+ # time, so no primary keys are declared and the table stays full refresh.+ items=lambda: get_custom_query_rows(user_id, custom_dataset_name, custom_params),+ primary_keys=None,+ )+++def validate_credentials(user_id: str) -> tuple[bool, str | None]:+ if not user_id or not user_id.strip():+ return False, f"{AUTH_ERROR_MESSAGE}. Register a free UserID at https://apps.bea.gov/api/signup/"++ session = make_tracked_session(redact_values=(user_id,))+ url = build_query_url(user_id, "GetParameterList", VALIDATION_DATASET_NAME)+ try:+ response = session.get(url, timeout=30)+ payload = response.json()+ except Exception:+ return False, "Could not reach the BEA API. Please try again later."++ try:+ _raise_for_error(response, payload)+ except UsBeaAuthenticationError:+ return False, f"{AUTH_ERROR_MESSAGE}. Register a free UserID at https://apps.bea.gov/api/signup/"+ except UsBeaApiError:+ return False, "BEA API returned an unexpected response. Please try again later."++ return True, None