eolas-data 1.14.0__tar.gz → 1.14.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. {eolas_data-1.14.0 → eolas_data-1.14.2}/.github/workflows/pre-release.yml +3 -0
  2. {eolas_data-1.14.0 → eolas_data-1.14.2}/.github/workflows/publish.yml +3 -0
  3. {eolas_data-1.14.0 → eolas_data-1.14.2}/CHANGELOG.md +46 -0
  4. {eolas_data-1.14.0 → eolas_data-1.14.2}/PKG-INFO +6 -5
  5. {eolas_data-1.14.0 → eolas_data-1.14.2}/README.md +1 -1
  6. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/__init__.py +2 -2
  7. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/_dataset_names.py +21 -17
  8. eolas_data-1.14.2/eolas_data/_regen_names.py +106 -0
  9. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/cli.py +4 -5
  10. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/client.py +85 -14
  11. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/library.py +21 -4
  12. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/mcp_server.py +1 -1
  13. eolas_data-1.14.2/eolas_data/py.typed +0 -0
  14. {eolas_data-1.14.0 → eolas_data-1.14.2}/pyproject.toml +5 -5
  15. {eolas_data-1.14.0 → eolas_data-1.14.2}/scripts/preflight.sh +4 -0
  16. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/conftest.py +6 -0
  17. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_cli.py +39 -0
  18. eolas_data-1.14.2/tests/test_packaging.py +7 -0
  19. eolas_data-1.14.2/tests/test_regen_names.py +55 -0
  20. eolas_data-1.14.2/tests/test_retries.py +152 -0
  21. eolas_data-1.14.0/eolas_data/_regen_names.py +0 -58
  22. {eolas_data-1.14.0 → eolas_data-1.14.2}/.github/workflows/catalog-drift.yml +0 -0
  23. {eolas_data-1.14.0 → eolas_data-1.14.2}/.github/workflows/smoke.yml +0 -0
  24. {eolas_data-1.14.0 → eolas_data-1.14.2}/.github/workflows/test.yml +0 -0
  25. {eolas_data-1.14.0 → eolas_data-1.14.2}/.gitignore +0 -0
  26. {eolas_data-1.14.0 → eolas_data-1.14.2}/LICENSE +0 -0
  27. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/cdc.py +0 -0
  28. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/console.py +0 -0
  29. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/dataset.py +0 -0
  30. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/exceptions.py +0 -0
  31. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/meta.py +0 -0
  32. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/reshape.py +0 -0
  33. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/rows.py +0 -0
  34. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/schedule.py +0 -0
  35. {eolas_data-1.14.0 → eolas_data-1.14.2}/eolas_data/search.py +0 -0
  36. {eolas_data-1.14.0 → eolas_data-1.14.2}/scripts/check_client_contract.py +0 -0
  37. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/fixtures/source_helpers.json +0 -0
  38. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_as_arrow.py +0 -0
  39. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_cdc_roundtrip.py +0 -0
  40. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_changes_http.py +0 -0
  41. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_client.py +0 -0
  42. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_date_filter.py +0 -0
  43. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_geometry_param.py +0 -0
  44. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_get_local.py +0 -0
  45. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_keyring.py +0 -0
  46. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_library.py +0 -0
  47. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_mcp_integration.py +0 -0
  48. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_mcp_protocol.py +0 -0
  49. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_mcp_server.py +0 -0
  50. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_meta.py +0 -0
  51. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_plan_notices.py +0 -0
  52. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_preview_dimensions.py +0 -0
  53. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_progress.py +0 -0
  54. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_reshape.py +0 -0
  55. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_reshape_integration.py +0 -0
  56. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_resilience.py +0 -0
  57. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_rows.py +0 -0
  58. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_schedule.py +0 -0
  59. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_search.py +0 -0
  60. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_smoke_live.py +0 -0
  61. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_source_helpers.py +0 -0
  62. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_sync_bulk.py +0 -0
  63. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_sync_changes.py +0 -0
  64. {eolas_data-1.14.0 → eolas_data-1.14.2}/tests/test_truncation.py +0 -0
@@ -25,6 +25,9 @@ jobs:
25
25
  pip install "$WHL"
26
26
  pip install pytest responses geopandas shapely pandas pyarrow typer rich keyring
27
27
 
28
+ - name: Dataset-name snapshot is current (release gate)
29
+ run: python -m eolas_data._regen_names --check
30
+
28
31
  - name: Unit tests (installed package)
29
32
  run: pytest -q -m "not integration"
30
33
 
@@ -98,6 +98,9 @@ jobs:
98
98
  - name: Client contract matrix
99
99
  run: python scripts/check_client_contract.py
100
100
 
101
+ - name: Dataset-name snapshot is current (release gate)
102
+ run: python -m eolas_data._regen_names --check
103
+
101
104
  - name: pytest
102
105
  run: pytest -q -m "not integration"
103
106
 
@@ -3,6 +3,52 @@
3
3
  All notable changes to `eolas-data` are recorded here. This project follows
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 1.14.2
7
+
8
+ ### Changed
9
+
10
+ - Author is now Phil Donovan <phil@eolas.nz>.
11
+ - Dropped the `australia` keyword from the PyPI listing.
12
+
13
+ ## 1.14.1
14
+
15
+ ### Added
16
+
17
+ - **Automatic retries.** Read-only requests (GET/HEAD) that get HTTP 429, 500,
18
+ 502, 503 or 504 are retried up to 3 times with exponential backoff and jitter.
19
+ `Retry-After` is honoured, as seconds or as an HTTP date. A wait longer than 30
20
+ seconds is not waited out: the error is raised straight away. Plan refusals
21
+ (`trial_soft_cap`, `trial_expired`, `bulk_not_in_plan`) are never retried, and
22
+ nothing that changes data is retried. Use `Client(max_retries=0)` to turn it off.
23
+ - **`py.typed`** marker, so type checkers use the package's type hints and
24
+ dataset-name `Literal`s.
25
+ - **`python -m eolas_data._regen_names --check`** exits non-zero when the
26
+ dataset-name snapshot is out of date. It runs in the pre-release gate, the
27
+ publish workflow and `scripts/preflight.sh`, so a release can no longer ship a
28
+ stale snapshot. Both modes now print the names added and removed.
29
+
30
+ ### Changed
31
+
32
+ - **Dataset-name snapshot refreshed** (2026-11-28, 1,539 datasets). 9 names added
33
+ (`acc_sports_injury_data`, `acc_treatment_and_rehabilitation_service_costs`,
34
+ `ecan_tsunami_blue_zones`, `nz_addresses_changes`, `nz_building_outlines_changes`,
35
+ `nz_geographic_areas_table_2025`, `nz_geographic_areas_table_2026`,
36
+ `nz_meshblock_higher_geographies_2026`, `nz_property_titles_changes`) and 7
37
+ retired names removed (`gas_monthly_stats`, `geonet_quakes_recent`,
38
+ `geonet_strong_motion_sensors`, `geonet_volcanic_alert_levels`,
39
+ `jobs_online_monthly`, `oil_monthly_stats`, `rental_bonds_by_tla`).
40
+ - The `dev` extra now includes `keyring`, so `pip install -e ".[dev]"` runs the
41
+ test suite.
42
+ - Package description, keywords and CLI/MCP help say "data API" (not "statistical
43
+ data API"), and no longer say "Australia on roadmap".
44
+
45
+ ### Fixed
46
+
47
+ - **API key file is private from the moment it exists.** `eolas auth set-key` (and
48
+ the config-file writes for `library_dir`) now create `~/.eolas/config.json` with
49
+ mode 0600 instead of writing it and then running `chmod`, and tighten a file
50
+ that already existed with wider permissions.
51
+
6
52
  ## 1.14.0
7
53
 
8
54
  ### Added
@@ -1,15 +1,15 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: eolas-data
3
- Version: 1.14.0
4
- Summary: Python client for the eolas.nz statistical data API (NZ + OECD; Australia on roadmap)
3
+ Version: 1.14.2
4
+ Summary: Python client for the eolas.nz data API (NZ and OECD data)
5
5
  Project-URL: Homepage, https://eolas.nz
6
6
  Project-URL: Documentation, https://docs.eolas.nz/
7
7
  Project-URL: Repository, https://github.com/phildonovan/eolas-data
8
8
  Project-URL: Bug Tracker, https://github.com/phildonovan/eolas-data/issues
9
- Author-email: Virtus Solutions <phil@virtus-solutions.io>
9
+ Author-email: Phil Donovan <phil@eolas.nz>
10
10
  License: MIT
11
11
  License-File: LICENSE
12
- Keywords: api,australia,economics,eolas,new-zealand,statistics
12
+ Keywords: api,data,economics,eolas,new-zealand
13
13
  Classifier: Development Status :: 4 - Beta
14
14
  Classifier: Intended Audience :: Developers
15
15
  Classifier: Intended Audience :: Science/Research
@@ -32,6 +32,7 @@ Requires-Dist: rich>=13; extra == 'cli'
32
32
  Requires-Dist: typer>=0.12; extra == 'cli'
33
33
  Provides-Extra: dev
34
34
  Requires-Dist: geopandas>=0.14; extra == 'dev'
35
+ Requires-Dist: keyring>=23.0; extra == 'dev'
35
36
  Requires-Dist: mcp<2,>=1.0; extra == 'dev'
36
37
  Requires-Dist: pandas; extra == 'dev'
37
38
  Requires-Dist: pytest; extra == 'dev'
@@ -58,7 +59,7 @@ Description-Content-Type: text/markdown
58
59
  [![Python](https://img.shields.io/pypi/pyversions/eolas-data)](https://pypi.org/project/eolas-data/)
59
60
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
60
61
 
61
- Python client for the [eolas.nz](https://eolas.nz) statistical data API — 1,500+ official New Zealand statistical & geospatial datasets, plus OECD data for international comparisons, served as tidy `pandas` DataFrames (or `polars` / `geopandas` if you prefer).
62
+ Python client for the [eolas.nz](https://eolas.nz) data API — 1,500+ official New Zealand datasets, geospatial layers included, plus OECD data for international comparisons, served as tidy `pandas` DataFrames (or `polars` / `geopandas` if you prefer).
62
63
 
63
64
  _Coverage is New Zealand + OECD today. Australian sources are on the roadmap — not yet available; OECD data already includes Australia (and other OECD members) for cross-country comparisons._
64
65
 
@@ -6,7 +6,7 @@
6
6
  [![Python](https://img.shields.io/pypi/pyversions/eolas-data)](https://pypi.org/project/eolas-data/)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
8
 
9
- Python client for the [eolas.nz](https://eolas.nz) statistical data API — 1,500+ official New Zealand statistical & geospatial datasets, plus OECD data for international comparisons, served as tidy `pandas` DataFrames (or `polars` / `geopandas` if you prefer).
9
+ Python client for the [eolas.nz](https://eolas.nz) data API — 1,500+ official New Zealand datasets, geospatial layers included, plus OECD data for international comparisons, served as tidy `pandas` DataFrames (or `polars` / `geopandas` if you prefer).
10
10
 
11
11
  _Coverage is New Zealand + OECD today. Australian sources are on the roadmap — not yet available; OECD data already includes Australia (and other OECD members) for cross-country comparisons._
12
12
 
@@ -1,4 +1,4 @@
1
- """eolas-data — Python client for the eolas.nz statistical data API."""
1
+ """eolas-data — Python client for the eolas.nz data API."""
2
2
 
3
3
  from importlib.metadata import PackageNotFoundError, version as _pkg_version
4
4
 
@@ -30,7 +30,7 @@ from .reshape import pivot_longer, pivot_wider
30
30
  try:
31
31
  __version__ = _pkg_version("eolas-data")
32
32
  except PackageNotFoundError: # pragma: no cover - uninstalled source checkout
33
- __version__ = "1.14.0"
33
+ __version__ = "1.14.2"
34
34
 
35
35
  __all__ = [
36
36
  "Client",
@@ -2,7 +2,7 @@
2
2
  Type stubs for dataset names.
3
3
 
4
4
  Auto-generated from https://api.eolas.nz/v1/datasets at release time.
5
- Snapshot: 2026-06-17 (1537 datasets).
5
+ Snapshot: 2026-11-28 (1539 datasets).
6
6
  Regenerate before each release with `python -m eolas_data._regen_names`.
7
7
 
8
8
  At runtime this is just a string — `Literal[...]` only constrains static type
@@ -11,8 +11,8 @@ it just doesn't autocomplete.
11
11
  """
12
12
  from typing import Literal
13
13
 
14
- CATALOG_SNAPSHOT_DATE = "2026-06-17"
15
- CATALOG_SNAPSHOT_COUNT = 1537
14
+ CATALOG_SNAPSHOT_DATE = "2026-11-28"
15
+ CATALOG_SNAPSHOT_COUNT = 1539
16
16
 
17
17
  DatasetName = Literal[
18
18
  'acc_achilles_tendon_ruptures',
@@ -75,9 +75,11 @@ DatasetName = Literal[
75
75
  'acc_sports_concussions_and_tbis',
76
76
  'acc_sports_concussions_in_southland',
77
77
  'acc_sports_injuries',
78
+ 'acc_sports_injury_data',
78
79
  'acc_sports_related_concussions_and_tbis',
79
80
  'acc_top_10_causes_of_injury_related_acc_payments_for_the_last_5_years',
80
81
  'acc_total_number_of_diagnostic_imaging_acc_claims_by_modality',
82
+ 'acc_treatment_and_rehabilitation_service_costs',
81
83
  'acc_treatment_injury_data',
82
84
  'acc_updated_data_for_rotator_cuff_injury_claims',
83
85
  'acc_washing_line_injuries',
@@ -309,6 +311,7 @@ DatasetName = Literal[
309
311
  'ecan_resource_consents_view',
310
312
  'ecan_river_public_access_sites',
311
313
  'ecan_school_enrolment_zones',
314
+ 'ecan_tsunami_blue_zones',
312
315
  'ecan_tsunami_evacuation_zones',
313
316
  'edcounts_achievement_and_attainment',
314
317
  'edcounts_apprenticeship_boost',
@@ -372,7 +375,6 @@ DatasetName = Literal[
372
375
  'fndc_sites_significance_maori',
373
376
  'fuel_prices_weekly',
374
377
  'fuel_prices_weekly_changes',
375
- 'gas_monthly_stats',
376
378
  'gdc_coastal_environment',
377
379
  'gdc_coastal_erosion',
378
380
  'gdc_coastal_flooding',
@@ -384,9 +386,6 @@ DatasetName = Literal[
384
386
  'gdc_scheduled_historic_buildings',
385
387
  'gdc_terrestrial_conservation_areas',
386
388
  'gdc_waahi_tapu',
387
- 'geonet_quakes_recent',
388
- 'geonet_strong_motion_sensors',
389
- 'geonet_volcanic_alert_levels',
390
389
  'gets_award_notices',
391
390
  'gets_product_categories',
392
391
  'gets_region_by_tender',
@@ -586,7 +585,6 @@ DatasetName = Literal[
586
585
  'iwi18_grp_grouping_religion',
587
586
  'iwi18_grp_grouping_sex',
588
587
  'iwi18_grp_grouping_ta',
589
- 'jobs_online_monthly',
590
588
  'jus_charges_by_offence_calendar',
591
589
  'jus_charges_by_offence_fiscal',
592
590
  'jus_charges_finalised_calendar',
@@ -845,6 +843,7 @@ DatasetName = Literal[
845
843
  'nrc_tsunami_inundation_2024',
846
844
  'nrc_tsunami_shore_evacuation_line',
847
845
  'nz_addresses',
846
+ 'nz_addresses_changes',
848
847
  'nz_addresses_road_sections',
849
848
  'nz_addresses_roads',
850
849
  'nz_area_unit_2001',
@@ -855,6 +854,7 @@ DatasetName = Literal[
855
854
  'nz_area_unit_2015',
856
855
  'nz_area_unit_2017',
857
856
  'nz_building_outlines',
857
+ 'nz_building_outlines_changes',
858
858
  'nz_cadastral_adjustments',
859
859
  'nz_cadastral_survey_network_marks',
860
860
  'nz_coastline_mean_high_water',
@@ -902,6 +902,8 @@ DatasetName = Literal[
902
902
  'nz_general_electorates_2025',
903
903
  'nz_geodetic_marks',
904
904
  'nz_geodetic_vertical_marks',
905
+ 'nz_geographic_areas_table_2025',
906
+ 'nz_geographic_areas_table_2026',
905
907
  'nz_government_gnss_cors',
906
908
  'nz_interest_long',
907
909
  'nz_interest_short',
@@ -955,6 +957,7 @@ DatasetName = Literal[
955
957
  'nz_meshblock_2025_v2',
956
958
  'nz_meshblock_2026',
957
959
  'nz_meshblock_higher_geographies_2025',
960
+ 'nz_meshblock_higher_geographies_2026',
958
961
  'nz_non_primary_linear_parcels',
959
962
  'nz_non_primary_parcels',
960
963
  'nz_nz_parcel_statutory_actions_list',
@@ -998,6 +1001,7 @@ DatasetName = Literal[
998
1001
  'nz_property_sale_type',
999
1002
  'nz_property_title_reference',
1000
1003
  'nz_property_titles',
1004
+ 'nz_property_titles_changes',
1001
1005
  'nz_property_untitled_land',
1002
1006
  'nz_property_untitled_land_reference_pilot',
1003
1007
  'nz_property_zoning',
@@ -1135,7 +1139,6 @@ DatasetName = Literal[
1135
1139
  'nzta_traffic_monitoring_sites',
1136
1140
  'odc_designated_areas',
1137
1141
  'odc_marae_locations',
1138
- 'oil_monthly_stats',
1139
1142
  'operational_alerts_campsites',
1140
1143
  'operational_alerts_huts',
1141
1144
  'opotiki_coastal_hazard_ohiwa',
@@ -1300,7 +1303,6 @@ DatasetName = Literal[
1300
1303
  'rdc_rng_outstanding_natural_landscape',
1301
1304
  'rdc_rng_tsunami_hazard_zones',
1302
1305
  'rental_bonds_by_region',
1303
- 'rental_bonds_by_tla',
1304
1306
  'rental_bonds_quarterly',
1305
1307
  'rlc_significant_natural_areas',
1306
1308
  'rlc_zoning',
@@ -1615,9 +1617,11 @@ ALL_NAMES: tuple[str, ...] = (
1615
1617
  'acc_sports_concussions_and_tbis',
1616
1618
  'acc_sports_concussions_in_southland',
1617
1619
  'acc_sports_injuries',
1620
+ 'acc_sports_injury_data',
1618
1621
  'acc_sports_related_concussions_and_tbis',
1619
1622
  'acc_top_10_causes_of_injury_related_acc_payments_for_the_last_5_years',
1620
1623
  'acc_total_number_of_diagnostic_imaging_acc_claims_by_modality',
1624
+ 'acc_treatment_and_rehabilitation_service_costs',
1621
1625
  'acc_treatment_injury_data',
1622
1626
  'acc_updated_data_for_rotator_cuff_injury_claims',
1623
1627
  'acc_washing_line_injuries',
@@ -1849,6 +1853,7 @@ ALL_NAMES: tuple[str, ...] = (
1849
1853
  'ecan_resource_consents_view',
1850
1854
  'ecan_river_public_access_sites',
1851
1855
  'ecan_school_enrolment_zones',
1856
+ 'ecan_tsunami_blue_zones',
1852
1857
  'ecan_tsunami_evacuation_zones',
1853
1858
  'edcounts_achievement_and_attainment',
1854
1859
  'edcounts_apprenticeship_boost',
@@ -1912,7 +1917,6 @@ ALL_NAMES: tuple[str, ...] = (
1912
1917
  'fndc_sites_significance_maori',
1913
1918
  'fuel_prices_weekly',
1914
1919
  'fuel_prices_weekly_changes',
1915
- 'gas_monthly_stats',
1916
1920
  'gdc_coastal_environment',
1917
1921
  'gdc_coastal_erosion',
1918
1922
  'gdc_coastal_flooding',
@@ -1924,9 +1928,6 @@ ALL_NAMES: tuple[str, ...] = (
1924
1928
  'gdc_scheduled_historic_buildings',
1925
1929
  'gdc_terrestrial_conservation_areas',
1926
1930
  'gdc_waahi_tapu',
1927
- 'geonet_quakes_recent',
1928
- 'geonet_strong_motion_sensors',
1929
- 'geonet_volcanic_alert_levels',
1930
1931
  'gets_award_notices',
1931
1932
  'gets_product_categories',
1932
1933
  'gets_region_by_tender',
@@ -2126,7 +2127,6 @@ ALL_NAMES: tuple[str, ...] = (
2126
2127
  'iwi18_grp_grouping_religion',
2127
2128
  'iwi18_grp_grouping_sex',
2128
2129
  'iwi18_grp_grouping_ta',
2129
- 'jobs_online_monthly',
2130
2130
  'jus_charges_by_offence_calendar',
2131
2131
  'jus_charges_by_offence_fiscal',
2132
2132
  'jus_charges_finalised_calendar',
@@ -2385,6 +2385,7 @@ ALL_NAMES: tuple[str, ...] = (
2385
2385
  'nrc_tsunami_inundation_2024',
2386
2386
  'nrc_tsunami_shore_evacuation_line',
2387
2387
  'nz_addresses',
2388
+ 'nz_addresses_changes',
2388
2389
  'nz_addresses_road_sections',
2389
2390
  'nz_addresses_roads',
2390
2391
  'nz_area_unit_2001',
@@ -2395,6 +2396,7 @@ ALL_NAMES: tuple[str, ...] = (
2395
2396
  'nz_area_unit_2015',
2396
2397
  'nz_area_unit_2017',
2397
2398
  'nz_building_outlines',
2399
+ 'nz_building_outlines_changes',
2398
2400
  'nz_cadastral_adjustments',
2399
2401
  'nz_cadastral_survey_network_marks',
2400
2402
  'nz_coastline_mean_high_water',
@@ -2442,6 +2444,8 @@ ALL_NAMES: tuple[str, ...] = (
2442
2444
  'nz_general_electorates_2025',
2443
2445
  'nz_geodetic_marks',
2444
2446
  'nz_geodetic_vertical_marks',
2447
+ 'nz_geographic_areas_table_2025',
2448
+ 'nz_geographic_areas_table_2026',
2445
2449
  'nz_government_gnss_cors',
2446
2450
  'nz_interest_long',
2447
2451
  'nz_interest_short',
@@ -2495,6 +2499,7 @@ ALL_NAMES: tuple[str, ...] = (
2495
2499
  'nz_meshblock_2025_v2',
2496
2500
  'nz_meshblock_2026',
2497
2501
  'nz_meshblock_higher_geographies_2025',
2502
+ 'nz_meshblock_higher_geographies_2026',
2498
2503
  'nz_non_primary_linear_parcels',
2499
2504
  'nz_non_primary_parcels',
2500
2505
  'nz_nz_parcel_statutory_actions_list',
@@ -2538,6 +2543,7 @@ ALL_NAMES: tuple[str, ...] = (
2538
2543
  'nz_property_sale_type',
2539
2544
  'nz_property_title_reference',
2540
2545
  'nz_property_titles',
2546
+ 'nz_property_titles_changes',
2541
2547
  'nz_property_untitled_land',
2542
2548
  'nz_property_untitled_land_reference_pilot',
2543
2549
  'nz_property_zoning',
@@ -2675,7 +2681,6 @@ ALL_NAMES: tuple[str, ...] = (
2675
2681
  'nzta_traffic_monitoring_sites',
2676
2682
  'odc_designated_areas',
2677
2683
  'odc_marae_locations',
2678
- 'oil_monthly_stats',
2679
2684
  'operational_alerts_campsites',
2680
2685
  'operational_alerts_huts',
2681
2686
  'opotiki_coastal_hazard_ohiwa',
@@ -2840,7 +2845,6 @@ ALL_NAMES: tuple[str, ...] = (
2840
2845
  'rdc_rng_outstanding_natural_landscape',
2841
2846
  'rdc_rng_tsunami_hazard_zones',
2842
2847
  'rental_bonds_by_region',
2843
- 'rental_bonds_by_tla',
2844
2848
  'rental_bonds_quarterly',
2845
2849
  'rlc_significant_natural_areas',
2846
2850
  'rlc_zoning',
@@ -0,0 +1,106 @@
1
+ """Regenerate ``_dataset_names.py`` from the live API.
2
+
3
+ Run before each release:
4
+
5
+ python -m eolas_data._regen_names # rewrite the snapshot
6
+ python -m eolas_data._regen_names --check # exit 1 if the snapshot is stale
7
+
8
+ ``GET /v1/datasets`` is public, so no API key is needed. If a key is set it is
9
+ used as normal (env var -> keyring -> ``~/.eolas/config.json``).
10
+
11
+ Both modes print the names added to and removed from the catalogue since the
12
+ last snapshot. ``--check`` writes nothing; it is the release gate run by the
13
+ ``Pre-release gate`` and ``Publish to PyPI`` workflows and by
14
+ ``scripts/preflight.sh``, so a release cannot ship a stale snapshot.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import datetime as _dt
19
+ import pathlib as _pathlib
20
+ import sys as _sys
21
+
22
+ _OUT = _pathlib.Path(__file__).with_name("_dataset_names.py")
23
+
24
+
25
+ def _live_names() -> list[str]:
26
+ from .client import Client
27
+
28
+ df = Client().list()
29
+ return sorted(df["name"].tolist())
30
+
31
+
32
+ def _snapshot_names() -> list[str]:
33
+ from ._dataset_names import ALL_NAMES
34
+
35
+ return list(ALL_NAMES)
36
+
37
+
38
+ def _diff(old: list[str], new: list[str]) -> tuple[list[str], list[str]]:
39
+ return sorted(set(new) - set(old)), sorted(set(old) - set(new))
40
+
41
+
42
+ def _print_diff(added: list[str], removed: list[str]) -> None:
43
+ print(f"added ({len(added)}):")
44
+ for n in added:
45
+ print(f" + {n}")
46
+ print(f"removed ({len(removed)}):")
47
+ for n in removed:
48
+ print(f" - {n}")
49
+
50
+
51
+ def check() -> int:
52
+ """Return 0 if the shipped snapshot matches the live catalogue, else 1."""
53
+ added, removed = _diff(_snapshot_names(), _live_names())
54
+ if not added and not removed:
55
+ print("dataset-name snapshot is current")
56
+ return 0
57
+ _print_diff(added, removed)
58
+ print(
59
+ "dataset-name snapshot is STALE - run `python -m eolas_data._regen_names`, "
60
+ "commit the result, then release.",
61
+ file=_sys.stderr,
62
+ )
63
+ return 1
64
+
65
+
66
+ def regenerate() -> None:
67
+ names = _live_names()
68
+ added, removed = _diff(_snapshot_names(), names)
69
+ today = _dt.date.today().isoformat()
70
+
71
+ out = _OUT
72
+ lines: list[str] = []
73
+ lines.append('"""')
74
+ lines.append("Type stubs for dataset names.")
75
+ lines.append("")
76
+ lines.append("Auto-generated from https://api.eolas.nz/v1/datasets at release time.")
77
+ lines.append(f"Snapshot: {today} ({len(names)} datasets).")
78
+ lines.append("Regenerate before each release with `python -m eolas_data._regen_names`.")
79
+ lines.append("")
80
+ lines.append("At runtime this is just a string — `Literal[...]` only constrains static type")
81
+ lines.append("checkers like mypy/pyright, so passing a name not in this list still works,")
82
+ lines.append("it just doesn't autocomplete.")
83
+ lines.append('"""')
84
+ lines.append("from typing import Literal")
85
+ lines.append("")
86
+ lines.append(f'CATALOG_SNAPSHOT_DATE = "{today}"')
87
+ lines.append(f"CATALOG_SNAPSHOT_COUNT = {len(names)}")
88
+ lines.append("")
89
+ lines.append("DatasetName = Literal[")
90
+ for n in names:
91
+ lines.append(f" {n!r},")
92
+ lines.append("]")
93
+ lines.append("")
94
+ lines.append("ALL_NAMES: tuple[str, ...] = (")
95
+ for n in names:
96
+ lines.append(f" {n!r},")
97
+ lines.append(")")
98
+ out.write_text("\n".join(lines) + "\n")
99
+ print(f"wrote {len(names)} datasets to {out}")
100
+ _print_diff(added, removed)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ if "--check" in _sys.argv[1:]:
105
+ raise SystemExit(check())
106
+ regenerate()
@@ -35,7 +35,7 @@ from .client import (
35
35
  _KEYRING_USERNAME,
36
36
  _keyring_get,
37
37
  )
38
- from .library import library_clear, library_set, library_status
38
+ from .library import _write_private_file, library_clear, library_set, library_status
39
39
  from .exceptions import (
40
40
  APIError,
41
41
  AuthenticationError,
@@ -65,8 +65,8 @@ EXIT_USAGE = 64 # convention from sysexits.h
65
65
  app = typer.Typer(
66
66
  name="eolas",
67
67
  help=(
68
- "CLI for the eolas.nz statistical data API. Browse and fetch 1,400+ "
69
- "official NZ statistical & geospatial datasets, plus OECD data for "
68
+ "CLI for the eolas.nz data API. Browse and fetch 1,400+ "
69
+ "official NZ data & geospatial datasets, plus OECD data for "
70
70
  "international comparisons. Pipes cleanly into jq, csvkit, etc."
71
71
  ),
72
72
  no_args_is_help=True,
@@ -1013,8 +1013,7 @@ def auth_set_key(
1013
1013
  ) -> None:
1014
1014
  """Save your API key to ~/.eolas/config.json."""
1015
1015
  CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
1016
- CONFIG_FILE.write_text(json.dumps({"api_key": api_key}, indent=2) + "\n")
1017
- CONFIG_FILE.chmod(0o600)
1016
+ _write_private_file(CONFIG_FILE, json.dumps({"api_key": api_key}, indent=2) + "\n")
1018
1017
  typer.echo(f"saved {CONFIG_FILE}")
1019
1018
  _show_plan_notice(api_key)
1020
1019
 
@@ -6,7 +6,10 @@ import json
6
6
  import logging
7
7
  import os
8
8
  import pathlib
9
+ import random
9
10
  import sys
11
+ import time
12
+ from email.utils import parsedate_to_datetime
10
13
  from dataclasses import dataclass
11
14
  from typing import Literal, Optional, Union
12
15
 
@@ -58,29 +61,91 @@ BASE_URL = _default_base_url()
58
61
  _DEFAULT_TIMEOUT = (10, 300)
59
62
 
60
63
 
64
+ # Bounded automatic retry for transient failures (M-P1). Only idempotent
65
+ # methods are retried, and only for these statuses. A 429 that carries one of
66
+ # our plan-error codes (trial_soft_cap etc.) is a refusal, not congestion, so it
67
+ # is never retried. Waits are capped so a huge Retry-After fails fast instead of
68
+ # hanging the caller.
69
+ _DEFAULT_MAX_RETRIES = 3
70
+ _RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
71
+ _RETRY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
72
+ _BACKOFF_BASE = 0.5 # seconds; doubles each attempt, with jitter
73
+ _BACKOFF_MAX = 30.0 # longest single wait, and the longest Retry-After honoured
74
+
75
+ # Indirection so tests can run without really sleeping.
76
+ _sleep = time.sleep
77
+
78
+
79
+ def _parse_retry_after(value: Optional[str]) -> Optional[float]:
80
+ """Seconds to wait from a ``Retry-After`` header (delta-seconds or HTTP-date).
81
+
82
+ Returns ``None`` when the header is absent or unparseable.
83
+ """
84
+ if not value:
85
+ return None
86
+ value = value.strip()
87
+ try:
88
+ return max(0.0, float(value))
89
+ except ValueError:
90
+ pass
91
+ try:
92
+ when = parsedate_to_datetime(value)
93
+ except (TypeError, ValueError):
94
+ return None
95
+ if when.tzinfo is None:
96
+ when = when.replace(tzinfo=datetime.timezone.utc)
97
+ return max(0.0, (when - datetime.datetime.now(datetime.timezone.utc)).total_seconds())
98
+
99
+
61
100
  class _TimeoutSession(requests.Session):
62
101
  """A ``requests.Session`` that applies a default timeout to every request.
63
102
 
64
103
  Single seam so ``get``/``head``/``post`` — and any future call site — carry
65
104
  a timeout without threading it through each call. A per-call ``timeout=``
66
105
  still wins via ``setdefault``.
106
+
107
+ It also retries transient HTTP failures (429 and 500/502/503/504) for
108
+ idempotent methods only (GET/HEAD/OPTIONS): up to ``max_retries`` extra
109
+ attempts with exponential backoff and jitter, honouring ``Retry-After``.
67
110
  """
68
111
 
69
- def __init__(self, timeout):
112
+ def __init__(self, timeout, max_retries: int = _DEFAULT_MAX_RETRIES):
70
113
  super().__init__()
71
114
  self._default_timeout = timeout
72
-
73
- def request(self, *args, **kwargs): # type: ignore[override]
115
+ self._max_retries = max(0, int(max_retries))
116
+
117
+ def _retry_delay(self, resp, attempt: int) -> Optional[float]:
118
+ """Seconds to wait before retrying *resp*, or ``None`` to give up."""
119
+ if resp.status_code == 429 and (resp.headers.get("X-Eolas-Error-Code") or "").strip() in _PLAN_ERROR_CODES:
120
+ return None # plan refusal, not congestion
121
+ wait = _parse_retry_after(resp.headers.get("Retry-After"))
122
+ if wait is not None:
123
+ return wait if wait <= _BACKOFF_MAX else None
124
+ ceiling = min(_BACKOFF_MAX, _BACKOFF_BASE * (2**attempt))
125
+ return random.uniform(ceiling / 2, ceiling)
126
+
127
+ def request(self, method, *args, **kwargs): # type: ignore[override]
74
128
  kwargs.setdefault("timeout", self._default_timeout)
75
- try:
76
- return super().request(*args, **kwargs)
77
- except requests.RequestException as exc:
78
- # Transport-level failure (connection refused, DNS, timeout, reset):
79
- # turn the raw urllib3/requests traceback into a typed EolasError so
80
- # callers (and the CLI's EolasError handler) get a clean message
81
- # instead of a stack dump (EH-2). HTTP status errors don't come
82
- # through here — the client inspects resp.status_code directly.
83
- raise EolasError(f"Network error talking to api.eolas.nz: {exc}") from exc
129
+ retryable = str(method).upper() in _RETRY_METHODS
130
+ attempt = 0
131
+ while True:
132
+ try:
133
+ resp = super().request(method, *args, **kwargs)
134
+ except requests.RequestException as exc:
135
+ # Transport-level failure (connection refused, DNS, timeout, reset):
136
+ # turn the raw urllib3/requests traceback into a typed EolasError so
137
+ # callers (and the CLI's EolasError handler) get a clean message
138
+ # instead of a stack dump (EH-2). HTTP status errors don't come
139
+ # through here — the client inspects resp.status_code directly.
140
+ raise EolasError(f"Network error talking to api.eolas.nz: {exc}") from exc
141
+ if not (retryable and resp.status_code in _RETRY_STATUSES and attempt < self._max_retries):
142
+ return resp
143
+ delay = self._retry_delay(resp, attempt)
144
+ if delay is None:
145
+ return resp
146
+ resp.close()
147
+ _sleep(delay)
148
+ attempt += 1
84
149
 
85
150
 
86
151
  # Geometry columns excluded when a caller passes geometry=False. `geometry_wkt`
@@ -237,7 +302,7 @@ def _to_geodataframe(df: "pd.DataFrame", force: bool = False):
237
302
 
238
303
 
239
304
  class Client:
240
- """Client for the eolas.nz statistical data API.
305
+ """Client for the eolas.nz data API.
241
306
 
242
307
  Args:
243
308
  api_key: Your API key. Falls back, in order, to the ``EOLAS_API_KEY``
@@ -247,6 +312,11 @@ class Client:
247
312
  or ``EOLAS_BASE_URL`` if that was set before import.
248
313
  cache: Cache responses in memory for the lifetime of the client.
249
314
  Useful in notebooks to avoid re-fetching on re-runs.
315
+ max_retries: Extra attempts for transient failures (HTTP 429, 500, 502,
316
+ 503, 504) on read-only requests, with exponential backoff and
317
+ jitter, honouring ``Retry-After``. Default 3; ``0`` turns
318
+ retries off. Plan refusals (e.g. ``trial_soft_cap``) are
319
+ never retried.
250
320
 
251
321
  Examples::
252
322
 
@@ -271,6 +341,7 @@ class Client:
271
341
  base_url: str = BASE_URL,
272
342
  cache: bool = False,
273
343
  timeout: tuple[float, float] | float = _DEFAULT_TIMEOUT,
344
+ max_retries: int = _DEFAULT_MAX_RETRIES,
274
345
  ):
275
346
  # Precedence: explicit arg → EOLAS_API_KEY env var → OS keyring →
276
347
  # ~/.eolas/config.json → "". The config-file step mirrors the CLI's
@@ -285,7 +356,7 @@ class Client:
285
356
  self._base = base_url.rstrip("/")
286
357
  self._cache: dict | None = {} if cache else None
287
358
  self._timeout = timeout
288
- self._session = _TimeoutSession(timeout)
359
+ self._session = _TimeoutSession(timeout, max_retries)
289
360
  # Explicit User-Agent: good API-client hygiene, and insulation against
290
361
  # the Cloudflare edge tightening bot rules (raw default UAs can be
291
362
  # 403'd by managed rulesets — a custom UA is always allowed).
@@ -304,6 +304,25 @@ def _read_library_dir_from_config() -> str:
304
304
  return ""
305
305
 
306
306
 
307
+ def _write_private_file(path, text: str) -> None:
308
+ """Write *text* to *path* so the file is never readable by others.
309
+
310
+ The file is created with mode 0600 (``os.open``), so there is no window where
311
+ it exists with the default umask. If it already existed with wider
312
+ permissions, ``os.fchmod`` tightens it before any key is written.
313
+ """
314
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
315
+ try:
316
+ if hasattr(os, "fchmod"): # not on Windows
317
+ os.fchmod(fd, 0o600)
318
+ with os.fdopen(fd, "w") as fh:
319
+ fd = -1 # fdopen now owns the descriptor
320
+ fh.write(text)
321
+ finally:
322
+ if fd != -1:
323
+ os.close(fd)
324
+
325
+
307
326
  def _write_config_key(key: str, value: str) -> None:
308
327
  """Write (or update) a single key in ``~/.eolas/config.json``."""
309
328
  _CONFIG_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
@@ -314,8 +333,7 @@ def _write_config_key(key: str, value: str) -> None:
314
333
  except Exception:
315
334
  data = {}
316
335
  data[key] = value
317
- _CONFIG_FILE.write_text(json.dumps(data, indent=2) + "\n")
318
- _CONFIG_FILE.chmod(0o600)
336
+ _write_private_file(_CONFIG_FILE, json.dumps(data, indent=2) + "\n")
319
337
 
320
338
 
321
339
  def _remove_config_key(key: str) -> None:
@@ -325,8 +343,7 @@ def _remove_config_key(key: str) -> None:
325
343
  return
326
344
  data = json.loads(_CONFIG_FILE.read_text())
327
345
  data.pop(key, None)
328
- _CONFIG_FILE.write_text(json.dumps(data, indent=2) + "\n")
329
- _CONFIG_FILE.chmod(0o600)
346
+ _write_private_file(_CONFIG_FILE, json.dumps(data, indent=2) + "\n")
330
347
  except Exception:
331
348
  pass
332
349
 
@@ -31,7 +31,7 @@ _MCP_SEARCH_CAP = 50
31
31
  mcp = FastMCP(
32
32
  "eolas",
33
33
  instructions=(
34
- "Tools for the eolas.nz statistical & geospatial data API (NZ + OECD). "
34
+ "Tools for the eolas.nz data & geospatial API (NZ + OECD). "
35
35
  "Use eolas_search then eolas_info before fetching unknown dataset names. "
36
36
  "For whole datasets prefer eolas_sync (keeps a local file current) or "
37
37
  "eolas_download (one-shot bulk file). Use eolas_get only for small slices."
File without changes
@@ -4,11 +4,11 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "eolas-data"
7
- version = "1.14.0"
8
- description = "Python client for the eolas.nz statistical data API (NZ + OECD; Australia on roadmap)"
7
+ version = "1.14.2"
8
+ description = "Python client for the eolas.nz data API (NZ and OECD data)"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
11
- authors = [{ name = "Virtus Solutions", email = "phil@virtus-solutions.io" }]
11
+ authors = [{ name = "Phil Donovan", email = "phil@eolas.nz" }]
12
12
  requires-python = ">=3.10"
13
13
  dependencies = [
14
14
  "requests>=2.28",
@@ -21,7 +21,7 @@ dependencies = [
21
21
  # bare `pip install eolas-data` leaves a broken `eolas` command.
22
22
  "typer>=0.12",
23
23
  ]
24
- keywords = ["statistics", "economics", "api", "new-zealand", "australia", "eolas"]
24
+ keywords = ["data", "economics", "api", "new-zealand", "eolas"]
25
25
  classifiers = [
26
26
  "Development Status :: 4 - Beta",
27
27
  "Intended Audience :: Developers",
@@ -42,7 +42,7 @@ Repository = "https://github.com/phildonovan/eolas-data"
42
42
  "Bug Tracker" = "https://github.com/phildonovan/eolas-data/issues"
43
43
 
44
44
  [project.optional-dependencies]
45
- dev = ["pytest", "responses", "pandas", "geopandas>=0.14", "shapely>=2.0", "typer>=0.12", "rich>=13", "mcp>=1.0,<2"]
45
+ dev = ["pytest", "responses", "pandas", "geopandas>=0.14", "shapely>=2.0", "typer>=0.12", "rich>=13", "mcp>=1.0,<2", "keyring>=23.0"]
46
46
  polars = ["polars>=0.20"]
47
47
  geo = ["geopandas>=0.14", "shapely>=2.0"]
48
48
  cli = ["typer>=0.12", "rich>=13"]
@@ -18,6 +18,10 @@ cd "$(dirname "$0")/.."
18
18
 
19
19
  fail() { echo "❌ PREFLIGHT FAILED: $*" >&2; exit 1; }
20
20
 
21
+ echo "==> 0/4 dataset-name snapshot is current (live catalogue, no key needed)"
22
+ pip install -q -e ".[dev]" || fail "pip install -e .[dev] failed"
23
+ python -m eolas_data._regen_names --check || fail "dataset-name snapshot is stale - run: python -m eolas_data._regen_names, commit, then release"
24
+
21
25
  echo "==> 1/4 install dev deps"
22
26
  pip install -q -e ".[dev]" || fail "pip install -e .[dev] failed"
23
27
 
@@ -5,3 +5,9 @@ import pytest
5
5
  def _no_plan_notice_lookup(monkeypatch):
6
6
  """`eolas auth set-key` looks up /v1/me for a plan notice; keep tests offline."""
7
7
  monkeypatch.setenv("EOLAS_NO_NOTICE", "1")
8
+
9
+
10
+ @pytest.fixture(autouse=True)
11
+ def _no_retry_sleep(monkeypatch):
12
+ """Retries back off between attempts; never really sleep in unit tests."""
13
+ monkeypatch.setattr("eolas_data.client._sleep", lambda _s: None)
@@ -8,6 +8,8 @@ from __future__ import annotations
8
8
 
9
9
  import json
10
10
  import os
11
+ import pathlib
12
+ import stat
11
13
  from pathlib import Path
12
14
 
13
15
  import pytest
@@ -662,3 +664,40 @@ def test_download_unknown_freshness_exits_usage():
662
664
  result = runner.invoke(app, ["download", "nz_cpi",
663
665
  "--freshness", "yesterday", "--api-key", "k"])
664
666
  assert result.exit_code == cli_module.EXIT_USAGE
667
+
668
+
669
+ @pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")
670
+ def test_set_key_file_is_created_private_without_a_later_chmod(monkeypatch):
671
+ """The key file is created 0600 by os.open, not widened then chmod'ed (L-P1)."""
672
+ opened = []
673
+ real_open = os.open
674
+
675
+ def spy_open(path, flags, mode=0o777, *a, **kw):
676
+ opened.append((str(path), mode))
677
+ return real_open(path, flags, mode, *a, **kw)
678
+
679
+ def no_chmod(self, *a, **kw): # a path-based chmod after the write is the old bug
680
+ raise AssertionError("Path.chmod must not be used for the key file")
681
+
682
+ monkeypatch.setattr(os, "open", spy_open)
683
+ monkeypatch.setattr(pathlib.Path, "chmod", no_chmod)
684
+ old_umask = os.umask(0) # worst case: a permissive umask
685
+ try:
686
+ result = runner.invoke(app, ["auth", "set-key", "--key", "secrettoken123"])
687
+ finally:
688
+ os.umask(old_umask)
689
+ assert result.exit_code == 0
690
+ cfg = cli_module.CONFIG_FILE
691
+ assert (str(cfg), 0o600) in opened
692
+ assert stat.S_IMODE(cfg.stat().st_mode) == 0o600
693
+
694
+
695
+ @pytest.mark.skipif(os.name == "nt", reason="POSIX file modes")
696
+ def test_set_key_tightens_a_pre_existing_wide_file():
697
+ cfg = cli_module.CONFIG_FILE
698
+ cfg.parent.mkdir(parents=True, exist_ok=True)
699
+ cfg.write_text("{}")
700
+ cfg.chmod(0o644)
701
+ result = runner.invoke(app, ["auth", "set-key", "--key", "secrettoken123"])
702
+ assert result.exit_code == 0
703
+ assert stat.S_IMODE(cfg.stat().st_mode) == 0o600
@@ -0,0 +1,7 @@
1
+ import pathlib
2
+
3
+ import eolas_data
4
+
5
+
6
+ def test_py_typed_marker_ships_with_the_package():
7
+ assert (pathlib.Path(eolas_data.__file__).parent / "py.typed").is_file()
@@ -0,0 +1,55 @@
1
+ """The dataset-name snapshot and its release gate (review M-S1, 2026-11-28)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+
7
+ from eolas_data import _regen_names as regen
8
+ from eolas_data._dataset_names import ALL_NAMES, CATALOG_SNAPSHOT_COUNT
9
+
10
+
11
+ def test_snapshot_is_internally_consistent():
12
+ assert CATALOG_SNAPSHOT_COUNT == len(ALL_NAMES) == len(set(ALL_NAMES))
13
+ assert list(ALL_NAMES) == sorted(ALL_NAMES)
14
+
15
+
16
+ def test_diff_reports_added_and_removed():
17
+ added, removed = regen._diff(["a", "b", "c"], ["b", "c", "d", "e"])
18
+ assert added == ["d", "e"]
19
+ assert removed == ["a"]
20
+
21
+
22
+ def test_check_passes_when_snapshot_matches_live(monkeypatch, capsys):
23
+ monkeypatch.setattr(regen, "_live_names", lambda: sorted(ALL_NAMES))
24
+ assert regen.check() == 0
25
+ assert "current" in capsys.readouterr().out
26
+
27
+
28
+ def test_check_fails_and_names_the_drift(monkeypatch, capsys):
29
+ live = sorted(set(ALL_NAMES) - {ALL_NAMES[0]} | {"brand_new_dataset"})
30
+ monkeypatch.setattr(regen, "_live_names", lambda: live)
31
+ assert regen.check() == 1
32
+ out = capsys.readouterr().out
33
+ assert "+ brand_new_dataset" in out
34
+ assert f"- {ALL_NAMES[0]}" in out
35
+
36
+
37
+ def test_regenerate_writes_a_loadable_snapshot(monkeypatch, tmp_path):
38
+ out = tmp_path / "_dataset_names.py"
39
+ monkeypatch.setattr(regen, "_OUT", out)
40
+ monkeypatch.setattr(regen, "_live_names", lambda: ["alpha", "zeta"])
41
+ monkeypatch.setattr(regen, "_snapshot_names", lambda: ["alpha", "old"])
42
+ regen.regenerate()
43
+ ns: dict = {}
44
+ exec(out.read_text(), ns)
45
+ assert ns["ALL_NAMES"] == ("alpha", "zeta")
46
+ assert ns["CATALOG_SNAPSHOT_COUNT"] == 2
47
+
48
+
49
+ def test_live_names_does_not_need_a_key(monkeypatch):
50
+ class FakeClient:
51
+ def list(self):
52
+ return pd.DataFrame({"name": ["b", "a"]})
53
+
54
+ monkeypatch.setattr("eolas_data.client.Client", FakeClient)
55
+ assert regen._live_names() == ["a", "b"]
@@ -0,0 +1,152 @@
1
+ """Bounded retry with backoff for transient failures (review M-P1, 2026-11-28)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ from email.utils import format_datetime
7
+
8
+ import pytest
9
+ import responses as resp_lib
10
+
11
+ from eolas_data import Client
12
+ from eolas_data import client as client_mod
13
+ from eolas_data.client import _parse_retry_after
14
+ from eolas_data.exceptions import APIError, PlanError, RateLimitError
15
+
16
+ BASE = "https://api.eolas.nz"
17
+ URL = f"{BASE}/v1/datasets/nz_cpi"
18
+ OK = {"name": "nz_cpi"}
19
+
20
+
21
+ @pytest.fixture()
22
+ def sleeps(monkeypatch):
23
+ rec: list[float] = []
24
+ monkeypatch.setattr(client_mod, "_sleep", rec.append)
25
+ return rec
26
+
27
+
28
+ @pytest.fixture()
29
+ def client():
30
+ return Client("eolas_testkey123", base_url=BASE)
31
+
32
+
33
+ @resp_lib.activate
34
+ @pytest.mark.parametrize("status", [429, 500, 502, 503, 504])
35
+ def test_transient_status_is_retried_then_succeeds(client, sleeps, status):
36
+ resp_lib.add(resp_lib.GET, URL, status=status)
37
+ resp_lib.add(resp_lib.GET, URL, status=status)
38
+ resp_lib.add(resp_lib.GET, URL, json=OK, status=200)
39
+ assert client.info("nz_cpi") == OK
40
+ assert len(resp_lib.calls) == 3
41
+ assert len(sleeps) == 2
42
+
43
+
44
+ @resp_lib.activate
45
+ def test_retries_are_bounded(client, sleeps):
46
+ resp_lib.add(resp_lib.GET, URL, status=503, body="down")
47
+ with pytest.raises(APIError) as exc:
48
+ client.info("nz_cpi")
49
+ assert exc.value.status_code == 503
50
+ assert len(resp_lib.calls) == 4 # 1 try + 3 retries
51
+ assert len(sleeps) == 3
52
+
53
+
54
+ @resp_lib.activate
55
+ def test_backoff_grows_and_is_jittered_and_capped(client, sleeps):
56
+ resp_lib.add(resp_lib.GET, URL, status=502)
57
+ with pytest.raises(APIError):
58
+ client.info("nz_cpi")
59
+ # attempt n waits in [ceiling/2, ceiling], ceiling = 0.5 * 2**n
60
+ for n, wait in enumerate(sleeps):
61
+ ceiling = min(client_mod._BACKOFF_MAX, client_mod._BACKOFF_BASE * 2**n)
62
+ assert ceiling / 2 <= wait <= ceiling
63
+
64
+
65
+ @resp_lib.activate
66
+ def test_retry_after_seconds_is_honoured(client, sleeps):
67
+ resp_lib.add(resp_lib.GET, URL, status=429, headers={"Retry-After": "7"})
68
+ resp_lib.add(resp_lib.GET, URL, json=OK, status=200)
69
+ assert client.info("nz_cpi") == OK
70
+ assert sleeps == [7.0]
71
+
72
+
73
+ @resp_lib.activate
74
+ def test_retry_after_http_date_is_honoured(client, sleeps):
75
+ when = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=12)
76
+ resp_lib.add(
77
+ resp_lib.GET, URL, status=503, headers={"Retry-After": format_datetime(when, usegmt=True)}
78
+ )
79
+ resp_lib.add(resp_lib.GET, URL, json=OK, status=200)
80
+ assert client.info("nz_cpi") == OK
81
+ assert len(sleeps) == 1 and 8 <= sleeps[0] <= 12
82
+
83
+
84
+ @resp_lib.activate
85
+ def test_retry_after_longer_than_cap_fails_fast(client, sleeps):
86
+ resp_lib.add(resp_lib.GET, URL, status=429, headers={"Retry-After": "3600"})
87
+ with pytest.raises(RateLimitError):
88
+ client.info("nz_cpi")
89
+ assert len(resp_lib.calls) == 1
90
+ assert sleeps == []
91
+
92
+
93
+ @resp_lib.activate
94
+ def test_plan_refusal_429_is_not_retried(client, sleeps):
95
+ resp_lib.add(
96
+ resp_lib.GET,
97
+ URL,
98
+ status=429,
99
+ json={"detail": "Your trial request allowance is used up."},
100
+ headers={"X-Eolas-Error-Code": "trial_soft_cap"},
101
+ )
102
+ with pytest.raises(PlanError):
103
+ client.info("nz_cpi")
104
+ assert len(resp_lib.calls) == 1
105
+ assert sleeps == []
106
+
107
+
108
+ @resp_lib.activate
109
+ @pytest.mark.parametrize("status", [400, 401, 403, 404])
110
+ def test_client_errors_are_not_retried(client, sleeps, status):
111
+ resp_lib.add(resp_lib.GET, URL, status=status, json={"detail": "nope"})
112
+ with pytest.raises(Exception):
113
+ client.info("nz_cpi")
114
+ assert len(resp_lib.calls) == 1
115
+
116
+
117
+ @resp_lib.activate
118
+ def test_non_idempotent_methods_are_not_retried(client, sleeps):
119
+ resp_lib.add(resp_lib.POST, URL, status=503)
120
+ resp = client._session.post(URL, json={})
121
+ assert resp.status_code == 503
122
+ assert len(resp_lib.calls) == 1
123
+ assert sleeps == []
124
+
125
+
126
+ @resp_lib.activate
127
+ def test_head_is_retried(client, sleeps):
128
+ resp_lib.add(resp_lib.HEAD, URL, status=503)
129
+ resp_lib.add(resp_lib.HEAD, URL, status=200)
130
+ assert client._session.head(URL).status_code == 200
131
+ assert len(resp_lib.calls) == 2
132
+
133
+
134
+ @resp_lib.activate
135
+ def test_max_retries_zero_disables_retries(sleeps):
136
+ c = Client("k", base_url=BASE, max_retries=0)
137
+ resp_lib.add(resp_lib.GET, URL, status=503, body="down")
138
+ with pytest.raises(APIError):
139
+ c.info("nz_cpi")
140
+ assert len(resp_lib.calls) == 1
141
+
142
+
143
+ @pytest.mark.parametrize(
144
+ "value,expected",
145
+ [("5", 5.0), ("0", 0.0), ("1.5", 1.5), ("-3", 0.0), ("", None), (None, None), ("soon", None)],
146
+ )
147
+ def test_parse_retry_after(value, expected):
148
+ assert _parse_retry_after(value) == expected
149
+
150
+
151
+ def test_parse_retry_after_past_date_is_zero():
152
+ assert _parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT") == 0.0
@@ -1,58 +0,0 @@
1
- """Regenerate ``_dataset_names.py`` from the live API.
2
-
3
- Run before each release:
4
-
5
- python -m eolas_data._regen_names
6
-
7
- Uses the same API-key resolution as :class:`~eolas_data.client.Client`
8
- (env var → keyring → ``~/.eolas/config.json``). The catalog endpoint
9
- requires authentication.
10
-
11
- Writes to the same file inside the package. Commit the result.
12
- """
13
- from __future__ import annotations
14
-
15
- import datetime as _dt
16
- import pathlib as _pathlib
17
-
18
-
19
- def regenerate() -> None:
20
- from .client import Client
21
-
22
- df = Client().list()
23
- names = sorted(df["name"].tolist())
24
- today = _dt.date.today().isoformat()
25
-
26
- out = _pathlib.Path(__file__).with_name("_dataset_names.py")
27
- lines: list[str] = []
28
- lines.append('"""')
29
- lines.append("Type stubs for dataset names.")
30
- lines.append("")
31
- lines.append("Auto-generated from https://api.eolas.nz/v1/datasets at release time.")
32
- lines.append(f"Snapshot: {today} ({len(names)} datasets).")
33
- lines.append("Regenerate before each release with `python -m eolas_data._regen_names`.")
34
- lines.append("")
35
- lines.append("At runtime this is just a string — `Literal[...]` only constrains static type")
36
- lines.append("checkers like mypy/pyright, so passing a name not in this list still works,")
37
- lines.append("it just doesn't autocomplete.")
38
- lines.append('"""')
39
- lines.append("from typing import Literal")
40
- lines.append("")
41
- lines.append(f'CATALOG_SNAPSHOT_DATE = "{today}"')
42
- lines.append(f"CATALOG_SNAPSHOT_COUNT = {len(names)}")
43
- lines.append("")
44
- lines.append("DatasetName = Literal[")
45
- for n in names:
46
- lines.append(f" {n!r},")
47
- lines.append("]")
48
- lines.append("")
49
- lines.append("ALL_NAMES: tuple[str, ...] = (")
50
- for n in names:
51
- lines.append(f" {n!r},")
52
- lines.append(")")
53
- out.write_text("\n".join(lines) + "\n")
54
- print(f"wrote {len(names)} datasets to {out}")
55
-
56
-
57
- if __name__ == "__main__":
58
- regenerate()
File without changes
File without changes